项目场景:
移动端-input拍照和上传图片,兼容ios和安卓,使用原生input标签
问题描述
1. ios拍照后图片会出现旋转的问题 2.压缩图片 3.图片重写背景是黑色问题
解决方案:
写法:vue2
原生input元素
<input type="file" ref="IDcard" accept="image/*" @change="readImage" />
readImage 上传图片方法
readImage($event) {
let that = this;
var file = $event.target.files[0];
var reader = new window.FileReader();
reader.onload = () => {
EXIF.getData(file, function() {
//获取图片方向
let orientation = EXIF.getTag(that, "Orientation");
if (!orientation) orientation = 1;
that.orientation = orientation;
//压缩图片
that.compress(reader.result);
$event.target.value = null;
});
};
reader.readAsDataURL(file);
},
压缩图片方法
compress(res) {
let that = this;
var MAX_WH = 800;
let image=new Image();
image.onload = function() {
// 等比例缩放
if (image.height > MAX_WH) {
image.width *= MAX_WH / image.height;
image.height = MAX_WH;
}
if (image.width > MAX_WH) {
image.height *= MAX_WH / image.width;
image.width = MAX_WH;
}
var quality = 1;
var cvs = document.createElement("canvas");
var context = cvs.getContext("2d");
let width,height;
cvs.width = width = image.width;
cvs.height = height = image.height;
switch (that.orientation) {
case 6:
case 8:
cvs.width = height;
cvs.height =width;
break;
}
//解决ios图片旋转问题(旋转和坐标系移动)
switch (that.orientation) {
// case 1: 照片显示正常
//照片需要逆时针旋转180度
case 3:
context.translate(width, height);
context.rotate(Math.PI);
break;
//照片需要顺时针旋转90度
case 6:
context.rotate(0.5 * Math.PI);
context.translate(0, -height);
break;
// 照片需要逆时针旋转90度
case 8:
context.rotate(-0.5 * Math.PI);
context.translate(-width, 0);
break;
}
context.clearRect(0, 0, cvs.width, cvs.height);
// 去除canvas黑色背景
context.fillStyle = "#fff";
context.fillRect(0, 0, cvs.width, cvs.height);
context.drawImage(image, 0, 0, image.width, image.height);
let readerResult = cvs.toDataURL("image/jpeg", quality);
// 展示图片的地方,自行调整
if (that.choose==="IDcardFront") {
that.imgFront = readerResult;
that.$refs.imgFront.src = readerResult;
that.spanFront=false;
return;
}
that.imgBack = readerResult;
that.$refs.imgBack.src = readerResult;
that.spanBack=false;
};
image.src = res;
},