时间:2021-07-01 10:21:17 帮助过:22人阅读
想法:利用canvas重绘图片,保持宽高比不变,具体宽高根本具体情况而定。
代码 :
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; }
效果图 :
该效果图是在电脑端测试的,手机端类似:
备注 :
该方法转换成的是base64格式的图片,在前端页面代码里面看着很长,不舒服,有一个解决方法是等图片传到服务器之后,压缩后的图片直接显示服务器上的图片地址。
以上就是用canvas怎么压缩图片?的详细内容,更多请关注Gxl网其它相关文章!