Nowadays, the photos taken by mobile phones are often several megabytes in size. When users upload photos on their mobile phones, one consumes a lot of data and the other takes a long time to upload. In order to solve this problem, it is necessary to compress the pictures:
Idea: Use canvas to redraw the picture, keeping the aspect ratio unchanged. The specific width and height will depend on the specific situation.
Code:
html:
<input type="file" id="upload" /><p>压缩前:</p><img id="oldImg" src=""/><p>压缩后:</p><img id="newImg" src=""/>
js:
var oldImg = document.getElementById("oldImg");var newImg = document.getElementById("newImg");//创建一个隐藏的canvasvar canvas = document.createElement("canvas"); canvas.id = "myCanvas"; canvas.style.display = "none"; document.body.appendChild(canvas); var cxt = canvas.getContext('2d');var upload = document.getElementById("upload"); upload.onchange = function(){//获取input file里面的图片路径,该路径为blob格式var url = getObjectURL(this.files[0]); oldImg.src = url; canvasImg.src = oldImg.src; canvasImg.onload = function(){//这是一个过渡的img,当这个img加载完成时绘制到canvas上面var m = oldImg.height/oldImg.width; canvas.width = 375; canvas.height = canvas.width*m; cxt.drawImage(canvasImg,0,0,canvas.width,canvas.height);//canvas绘制完成则转换为base64并传到新的图片上,再删除canvasvar Pic = document.getElementById("myCanvas").toDataURL("image/png"); newImg.src = Pic; document.body.removeChild(canvas);} }//建立一個可存取到該file的urlfunction getObjectURL(file) {var url = null;if(window.createObjectURL != undefined) { // basicurl = window.createObjectURL(file); } else if(window.URL != undefined) { // mozilla(firefox)url = window.URL.createObjectURL(file); } else if(window.webkitURL != undefined) { // webkit or chromeurl = window.webkitURL.createObjectURL(file); }return url; }
Rendering:
The rendering was tested on the computer, and the mobile phone is similar:
Remark:
This method converts images in base64 format, which looks very long and uncomfortable in the front-end page code. One solution is to wait for the image to be transmitted to the server. , the compressed image directly displays the image address on the server.
The above is the detailed content of How to compress images using canvas?. For more information, please follow other related articles on the PHP Chinese website!