在使用苹果手机上传图片的时候,发现传完的图片显示出来方向是错误的,竖着的图片会变成横着显示(少部分安卓手机也存在这个问题)ios
ios 相机加入了方向传感器,它能够记录拍摄时的方向,而且记录在 exif 当中,因此这个时候竖拍的照片显示出来就会就会‘横’着了git
具体操做:github
const reader = new FileReader(); reader.onload = function() { const result = this.result; const photoImg = new Image(); photoImg.src = result; photoImg.onload = function() { // 生成canvas const canvas = document.createElement('canvas'); const width = photoImg.width; const height = photoImg.height; canvas.height = width; canvas.width = height; const ctx = canvas.getContext('2d'); EXIF.getData(photoImg, function() { // 获取 Orientation 信息 const Orientation = EXIF.getTag(this, 'Orientation'); // 根据 Orientation 信息修正方向 switch (Orientation) { case 6: ctx.rotate(Math.PI / 2); ctx.translate(0, -height); break; case 3: ctx.rotate(Math.PI); ctx.translate(-width, -height); break; case 8: ctx.rotate(-Math.PI / 2); ctx.translate(-height, 0); break; default: break; } // 将方向错误的图片绘制到 canvas 上 ctx.drawImage(photoImg, 0, 0); // 将方向修正后的 canvas 装化成 base64 编码 const newImg = canvas.toDataURL('image/jpeg'); message.hide(); resolve(newImg); }); }; }; reader.readAsDataURL(photo);
Orientation 参数对照canvas
exif 文档ide