ios上传图片显示方向错误问题

时间:2023-03-08 22:04:04

IOS 上传图片方向显示错误问题

问题描述

在使用苹果手机上传图片的时候,发现传完的图片显示出来方向是错误的,竖着的图片会变成横着显示(少部分安卓手机也存在这个问题)

产生原因

ios 相机加入了方向传感器,它可以记录拍摄时的方向,并且记录在 exif 当中,所以这个时候竖拍的照片显示出来就会就会‘横’着了

解决办法

  1. 获取图片的 Orientation 信息,也就是拍摄方向
  2. 绘制一个 canvas, 将该图片绘制上去,然后修正显示方向
  3. 将 canvas 转化成我们需要的格式

具体操作:

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 参数对照

ios上传图片显示方向错误问题

资料

exif 文档