canvas压缩图片苦逼经历记录
最近做报名系统,需要上传名片,并且自动读取名片信息填充表单的功能,考虑到用户可能使用手机摄像头拍摄照片,需要在客户端用canvas进行压缩后转base64字符串上传。
问题来了,苦逼得。。。FileReader读取用户选择的图片文件后复制给一个img dom对象(absolute定位,left,top设置一个很大的负值将图片不显示在课件区域),然后用canvas绘制这个img对象进行压缩,结果pc端,Android端都可以正常压缩,但是发现ios下图片除了会旋转外,还有一个很要命的问题,图片信息丢失了。。正常图片如下
ios压缩后的图片如下,图片丢失了一部分内容,变黑色的了。。
以为是ios自动旋转图片导致。网上找了n多代码,用exif获取拍照方向什么的,然后做旋转什么的,结果还是会丢失。最后核对了下代码,别人使用的是Image对象加载图片,而不是img标签。换成Image对象加载图片信息后问题就解决了,mmd哟,搞了半个下午。。
下面为示例代码,自己注释imgCompress对象的获取
<!DOCTYPE html> <html lang="zh"> <head> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta name="viewport" content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;" /> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>test</title> <style>img{max-width:100%}</style> </head> <body><img id="imgCompress" /> 压缩后<br> <img id="imgPrev" /><br /> <input type="file" onchange="readImg(this)" accept="image/*" /> <script> //var imgCompress = document.getElementById('imgCompress'); var imgCompress = new Image(); imgCompress.onload = function () { info.innerHTML += this.src.length + '<br>' + (imgPrev.src = compressImg(1500, 80, this)).length; } /* *width:最大宽度,超过等比缩放 *rate:压缩比率0~100,越小压缩越多 *img:图片,mmd,一定记住不要使用img dom对象,要使用Image加载,要不ios搞死人 */ window.compressImg = function (width, rate, img) { //使用naturalWidth,naturalHeight属性获取原始图片宽度和高度 //直接使用width,height属性用Image对象可以得到原始宽度高度,但是如果是img dom对象得到的是显示的尺寸 //这样drawImage只会绘制一小部分图片 var imgWidth = img.naturalWidth, imgHeight = img.naturalHeight, height = imgHeight; if (imgWidth > width) { height = Math.floor(width * imgHeight / imgWidth); } else width = imgWidth; var canvas = document.createElement("canvas"), ctx = canvas.getContext('2d'); canvas.width = width; canvas.height = height; ctx.drawImage(img, 0, 0, imgWidth, imgHeight, 0, 0, width, height); return canvas.toDataURL('image/jpeg', rate / 100); }; function readImg(file) { if (!/^image\//.test(file.files[0].type)) return; var reader = new FileReader(); reader.onload = function (e) { imgCompress.src = e.target.result; }; reader.readAsDataURL(file.files[0]); } </script> </body> </html>
加支付宝好友偷能量挖...
原创文章,转载请注明出处:canvas压缩图片苦逼经历记录