解决H5 IOS手机图片上传时图片会旋转90°问题
Vant 官方给出的解答需要自己解决,没有处理。
解决办法主要使用了 compressorjs 插件库
一、Vant UI库Uploader 组件图片上传:
<van-uploader
v-model="fileList"
:after-read="afterRead"
:before-read="beforeRead"
/>
import ImageCompressor from "image-compressor.js";
beforeRead(file) {
return new Promise((resolve) => {
new ImageCompressor(file, {
quality: 0.6,
success: resolve,
error(err) {
console.log(err.message);
},
});
});
},
二、compressorjs的安装使用
1、安装
npm install image-compressor.js
2、使用格式
file代表要压缩的图片,类型file或blob。
options可选的一些操作。checkOrientation指示是否读取图像的Exif方向值(仅为JPEG图像),然后使用该值自动旋转或翻转图像,默认true。quality可设置压缩质量,默认为1
new ImageCompressor(file,[options])
3、测试结果
ImageCompressor将file转成了blob格式,接口只支持file。需要做转换。
拍照后从相册上传图片不再旋转,直接拍照上传仍会旋转90°。(iPhone13 pro、13 pro max机型,其他未知)
4、最终方案
data(){
checkOrientation:true
},
created(){
let navigatorUserAgent = navigator.userAgent.match(
/CPU iPhone OS (.*?) like Mac OS/
);
// console.log(navigator.userAgent.match(/CPU iPhone OS (.*?) like Mac OS/));
// 当iPhone OS 11_0 >=13的版本时,设置checkOrientation: false;反之设置checkOrientation: true, 检查
if (navigatorUserAgent) {
let edition = navigatorUserAgent[1].split("_")[0];
~~edition >= 13
? (this.checkOrientation = false)
: (this.checkOrientation = true);
}
},
methods:{
// 解决手机拍照时图片会旋转问题
beforeRead(file) {
if (file.type.indexOf("image") == "-1") {
return file;
}
return new Promise((resolve) => {
// compressorjs 默认开启 checkOrientation 选项
// 会将图片修正为正确方向 Compressor
new ImageCompressor(file, {
quality: 0.6,
checkOrientation: this.checkOrientation,
success(res) {
res = new File([res], res.name, {
type: res.type,
lastModified: Date.now(),
});
resolve(res);
},
error(err) {
console.log(err.message);
},
});
});
},
}