使用场景,在作朋友圈 H5 时,时常遇到须要用户拍照上传图片需求,可是在一些手机(iso)上拍出来的照片会出现奇怪的旋转角度来呈现。通过各类百度才发现相机拍出来的图片拥有不少属性,其中一项是Orientation
,用于记录拍摄时相机物理旋转角度,例如把相机倒过来Orientation
是3
,顺时针竖起来Orientation
是6
,逆时针竖起来Orientation
是8
,正常模式Orientation
是1
。根据这个属性咱们能够使用Canvas来对图片重绘。css
import EXIF from 'exif-js'; // 引入依赖插件 // 参数列表:img 对象,callback返回Base64图片编码,生成图片质量默认值0.9 export const FixImg = (img, callback, quality = 0.9) => { let Orientation, ctxWidth, ctxHeight, base64; // 定义所需变量 EXIF.getData(img, function() { Orientation = EXIF.getTag(this, 'Orientation'); ctxWidth = this.naturalWidth; ctxHeight = this.naturalHeight; console.log(Orientation, ctxWidth, ctxHeight); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); canvas.width = ctxWidth; canvas.height = ctxHeight; if ([5, 6, 7, 8].includes(Orientation)) { canvas.width = ctxHeight; canvas.height = ctxWidth; } switch (Orientation) { case 2: ctx.transform(-1, 0, 0, 1, ctxWidth, 0); break; case 3: ctx.transform(-1, 0, 0, -1, ctxWidth, ctxHeight); break; case 4: ctx.transform(1, 0, 0, -1, 0, ctxHeight); break; case 5: ctx.transform(0, 1, 1, 0, 0, 0); break; case 6: ctx.transform(0, 1, -1, 0, ctxHeight, 0); break; case 7: ctx.transform(0, -1, -1, 0, ctxHeight, ctxWidth); break; case 8: ctx.transform(0, -1, 1, 0, 0, ctxWidth); break; default: ctx.transform(1, 0, 0, 1, 0, 0); } ctx.drawImage(img, 0, 0, ctxWidth, ctxHeight); // 默认输出jpeg,也能够读取原图片格式,最后输出原图格式,搜索关键词 :File.type base64 = canvas.toDataURL('image/jpeg', quality); callback(base64); }); };
性感照骗,在线修复: http://peichenhu.cn/demo/awesome/#/Exifhtml
相关补充:从图片 Exif 信息中取到 Orientation 后,就能够根据它来自动旋转图片了,canvas、filter 滤镜、vml、css3 均可以实现图片的旋转。
参考文章:https://imququ.com/post/how-t...css3