1、将base64转换为 file 对象
function () {
var arr = image.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
let file = new File([u8arr], i, {type:mime});
}
2、将 file 对象转换为 base64 图片
putImgData(file) {
let Orientation = null;
let self = this;
if (file) {
//获取照片方向角属性
Exif.getData(file, function () {
Exif.getAllTags(this);
Orientation = Exif.getTag(this, 'Orientation');
});
}
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
let image = new Image();
image.src = this.result;
image.onload = function () {
var width = this.naturalWidth;
var height = this.naturalHeight;
// var ratio = (width < height ? width / height : height / width) / 4;
let ratio;
if ((ratio = width * height / 4000000)>1) {
ratio = 1 / ratio;
}else {
ratio = 1;
}
let canvas = document.createElement("canvas");
canvas.width = width * ratio;
canvas.height = height * ratio;
var ctx = canvas.getContext("2d");
if (Orientation != "" && Orientation != 1 && Orientation !=undefined) {
switch (Orientation) {
case 6://需要顺时针90度旋转
canvas.width = height * ratio;
canvas.height = width * ratio;
ctx.rotate(90 * Math.PI / 180);
ctx.drawImage(this, 0, -height * ratio, width * ratio, height * ratio);
break;
case 8://需要逆时针90度旋转
canvas.width = height * ratio;
canvas.height = width * ratio;
ctx.rotate(-90 * Math.PI / 180);
ctx.drawImage(this, -width * ratio, 0, width * ratio, height * ratio);
break;
case 3://需要180度旋转
ctx.rotate(180 * Math.PI / 180);
ctx.drawImage(this, -width * ratio, -height * ratio, width * ratio, height * ratio);
break;
default:
ctx.drawImage(this, 0, 0, width, height, 0, 0, width * ratio, height * ratio);
break;
}
} else {
ctx.drawImage(this, 0, 0, width, height, 0, 0, width * ratio, height * ratio);
}
let base64 = canvas.toDataURL("image/jpeg", 0.3);
};
};
},