input文本框上传图片, 苹果和小米手机照片翻转问题 ,身份证照片前端判断是否横屏拍摄
HTML内容
<input type=""file accept="image/*" @change="uploadPic($event)">
uploadPic方法
import EXIF from"exif-js"
uploadPic(e, type, fn) {
//利用fileReader对象获取file
let file = e.target.files[0];
let filesize = file.size;
let that = this;
//去获取拍照时的信息
EXIF.getData(file, function () {
EXIF.getAllTags(this);
that.orientation = EXIF.getTag(this, "orientation")
});
if (filesize > 51200000) {
this.tkToast = {
title: "图片大小不超过50k",
duration: 3000
}
return false
}
let reader = new FileReader();
reader.onload = e => {
let result = e.target.result;
if (result.length <= 100 * 1024) {
this.faceImgid = result;
fn(this.faceImgid, type)
} else {
//base64图片大于10M 进行压缩
this.compress(result, this.orientation, type, fn)
}
};
reader.readAsDataURL(file);
},
compress压缩方法
compress(result, orientation, type, fn) {
let image = new Image();
image.src = result;
image.onload = () => {
let imgWidth = image.width,
imgHeight = image.height;
if (type === "cidz" || type === "cidf") {
//照片横屏前端判断
if (imgWidth < imgHeight) {
this.tkToast = {
title: "上传的照片格式不正确,请横屏拍摄",
duration: 3000
};
return false;
}
}
let canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d");
canvas.width = imgWidth;
canvas.height = imgHeight;
if (orientation && orientation != 1) {
switch (orientation) {
case 6:
if (type === "cidz" || type === "cidf") {
//照片横屏前端判断
this.tkToast = {
title: "上传的照片格式不正确,请横屏拍摄",
duration: 3000
};
break;
}
//旋转90°,苹果和小米手机自动识别照片的长边为canvas画布宽,所以竖屏拍照绘图时,canvas的宽高要对调
canvas.width = imgHeight;
canvas.height = imgWidth;
ctx.rotate(Math.PI / 2);
ctx.drawImage(image, -imgWidth, -imgHeight);
this.faceImageid = canvas.toDataURL("image/jpeg", 0.5);
break;
case 3://旋转180°
ctx.rotate(Math.PI);
ctx.drawImage(image, -imgWidth, -imgHeight);
this.faceImageid = canvas.toDataURL("image/jpeg", 0.5);
break;
case 8://旋转-90
if (type === "cidz" || type === "cidf") {
//照片横屏前端判断
this.tkToast = {
title: "上传的照片格式不正确,请横屏拍摄",
duration: 3000
};
break;
}
//旋转90°,苹果和小米手机自动识别照片的长边为canvas画布宽,所以竖屏拍照绘图时,canvas的宽高要对调
canvas.width = imgHeight;
canvas.height = imgWidth;
ctx.rotate((3*Math.PI) / 2);
ctx.drawImage(image, -imgWidth, -imgHeight);
this.faceImageid = canvas.toDataURL("image/jpeg", 0.5);
break;
}
}else{
ctx.drawImage(image,0,0,imgWidth,imgHeight);
this.faceImageid = canvas.toDataURL("image/jpeg", 0.5);
}
fn(this.faceImageid,type)
}
}