Home > Web Front-end > HTML Tutorial > HTML5 combined with canvas to achieve image compression

HTML5 combined with canvas to achieve image compression

零到壹度
Release: 2018-03-24 16:36:03
Original
1915 people have browsed it


This time I will bring you HTML5 combined with canvas to achieve image compression, which is mainly reflected in the form of code. The following is a practical case, let's take a look.

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <meta name=&#39;viewport&#39; content=&#39;width=device-width, initial-scale=1, maximum-scale=1&#39;>
 <title>lianxi </title>
 <style type="text/css">
    </style>
</head>
<body>
    <form>
 名字:<input type="text " name = &#39;username&#39; id = &#39;username&#39;/>
 上传:<input type="file" name = &#39;fileimage&#39; id = &#39;fileimage&#39; />
 </form>
 <button>button</button>
 <script>
 var file = document.querySelector(&#39;#fileimage&#39;)
 var username = document.querySelector(&#39;#username&#39;)
 var canvas = document.createElement(&#39;canvas&#39;);
 var span = document.createElement(&#39;span&#39;)
 var formData = new FormData()
 file.addEventListener(&#39;change&#39;,function() {
 //实现的原理的new formData()然后把这个formData 用ajax传进去
 span.innerHTML = &#39;预览图加载中...&#39;
 document.body.appendChild(span)
 console.log(file.files[0])
 username.value ? formData.append(&#39;username&#39;,username.value) : null;
 resize(file.files[0]);
 })
 //上传前的图片压缩
 function resize(file) {
 var reader = new FileReader()
 reader.readAsDataURL(file)
 var img = new Image()
 reader.onload = function (e) {
 // this.result就是图片的base64地址信息
 img.src = this.result;
 }
 
 var context = canvas.getContext(&#39;2d&#39;);
 var gif = document.createElement(&#39;img&#39;)
 
 // base64地址图片加载完毕后
 img.onload = function () {
 // 图片原始尺寸
 //定义画布的大小
 if (img.width > 300 || img.height > 300) {
 if (img.width > img.height) {
 canvas.width = 300
 canvas.height = img.height / img.width * 300
 }
 else {
 canvas.height = 300
 canvas.width = img.width / img.height * 300
 }
 }
 //从那里开始截取图片
 context.drawImage(img, 0, 0, canvas.width, canvas.height)
 /*第一个参数是创建的img对象;第二个参数是左上角坐标,后面两个是画布区域宽高*/
 //压缩后的图片base64 url
                /*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是&#39;image/jpeg&#39;;
                 * qualityArgument表示导出的图片质量,只要导出为jpg和webp格式的时候此参数才有效果,默认值是0.92*/
 //var newUrl = canvas.toDataURL(&#39;image/jpeg&#39;, 0.92);//base64 格式
 document.body.removeChild(span)
 document.querySelector(&#39;body&#39;).appendChild(canvas)
 };
 }
 //这是上传的
 document.querySelector(&#39;button&#39;).addEventListener(&#39;click&#39;,function(){
 canvas.toBlob(function(blob){
 var xhr = new XMLHttpRequest()
 formData.append(&#39;fileimage&#39;, blob,&#39;002.webp&#39;)
 xhr.open(&#39;POST&#39;, &#39;test.php&#39;, true)//默认true 为异步
 //上传进度
 xhr.upload.addEventListener(&#39;progress&#39;,function (e) {
 console.log(&#39;上传进度为:&#39;+ (e.loaded/e.total*100).toFixed(2)+&#39;%&#39;)//多次出现
 // event.total是需要传输的总字节,event.loaded是已经传输的字节
 })
 xhr.upload.addEventListener(&#39;loadstart&#39;, function () {
 console.log(&#39;上传开始&#39;)//只出现一次
 })
 xhr.onreadystatechange = function () {
 if (xhr.readyState === 4) {
 if (xhr.status >= 200 && xhr.status <300 || xhr.status == 304) {
 console.log(JSON.parse(xhr.responseText))//成功后的返回值
 }
 else {
 console.log("Request was unsuccessful: " + xhr.status);
 } 
 }
 
 }
 //xhr.setRequestHeader("Content-type", "multipart/form-data");
 xhr.send(formData)
 }, &#39;image/webp&#39;,0.9)
 })
 </script>
</body>
</html>
Copy after login

It should be noted that the backend needs to add header("Access-Control-Allow-Origin:*"); to achieve cross-domain

Related links:

html5+canvas implements image compression and upload

HTML5 Canvas implements local compression of images

HTML5 canvas implements image stretching, compression and cropping

The above is the detailed content of HTML5 combined with canvas to achieve image compression. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template