最近ios升级到13.5.1之后 input上传照片不需要再解决上传照片横屏的问题了
但这个版本之前的还是需要解决照片横屏问题
需要引入exif.js
github地址https://github.com/exif-js/exif-js
Orientation属性说明如下:
旋转角度参数
旋转角度 参数
0° 1
顺时针90° 6
逆时针90° 8
180° 3
下面附上代码
先判断手机是不是ios系统并获取版本号
var str = navigator.userAgent.toLowerCase();
var ver = str.match(/cpu iphone os (.*?) like mac os/);
if (ver) {
var curVer = ver[1].replace(/_/g, ".")
}
上传图片EXIF获取图片信息的orientation
$('#upload').on('change', function () {
var file = this.files[0];//获取file组件中的文件
var orientation;
EXIF.getData(file, function () {
orientation = EXIF.getTag(this, 'Orientation');
});
var reader = new FileReader();
reader.onload = function (e) {
getImgData(this.result, orientation, function (data) {
that.uploadImg = data
that.testImg(data)
});
};
reader.readAsDataURL(file);
});
根据判断系统版本号使用canvas旋转图片
function getImgData(img, dir, next) {
var image = new Image();
image.src = img;
image.onload = function () {
var degree = 0, drawWidth, drawHeight, width, height, scaleCanvas, curW, curH;
curW = drawWidth = this.width;
curH = drawHeight = this.height;
if (drawWidth > 729) {
scaleCanvas = 729 / drawWidth;
} else {
scaleCanvas = 1;
} //以下改变一下图片大小
var canvas = document.createElement('canvas');
canvas.width = width = drawWidth * scaleCanvas;
canvas.height = height = drawHeight * scaleCanvas;
var context = canvas.getContext('2d');//判断图片方向,重置canvas大小,确定旋转角度,iphone默认的是home键在右方的横屏拍摄方式
if (ver) {
var verArr = curVer.split('.')
if (verArr[0] = 13 && verArr[1] >= 5 && verArr[2] >= 1) {
context.drawImage(this, 0, 0, curW, curH, 0, 0, drawWidth * scaleCanvas, drawHeight * scaleCanvas);
} else if (verArr[0] > 13) {
context.drawImage(this, 0, 0, curW, curH, 0, 0, drawWidth * scaleCanvas, drawHeight * scaleCanvas);
} else {
switch (dir) {
//iphone横屏拍摄,此时home键在左侧
case 3:
degree = 180;
drawWidth = -width;
drawHeight = -height;
break;
//iphone竖屏拍摄,此时home键在下方(正常拿手机的方向)
case 6:
canvas.width = height;
canvas.height = width;
degree = 90;
drawWidth = width;
drawHeight = -height;
break;
//iphone竖屏拍摄,此时home键在上方
case 8:
canvas.width = height;
canvas.height = width;
degree = 270;
drawWidth = -width;
drawHeight = height;
break;
}
//使用canvas旋转校正
context.rotate(degree * Math.PI / 180);
if (dir == 3 || dir == 6 || dir == 8) {
context.drawImage(this, 0, 0, curW, curH, 0, 0, drawWidth, drawHeight);
} else {
context.drawImage(this, 0, 0, curW, curH, 0, 0, drawWidth * scaleCanvas, drawHeight * scaleCanvas);
}
}
} else {
context.drawImage(this, 0, 0, curW, curH, 0, 0, drawWidth * scaleCanvas, drawHeight * scaleCanvas);
}
//返回校正图片
next(canvas.toDataURL("image/jpeg", 1)); }}