1. npm下載exif-js包
文檔
npm install exif-js --save
用於獲取圖片的旋轉狀態
2.壓縮旋轉
compressImg(img, fileName) {
// 壓縮圖片
let Orientation = this.getExif(img); // 獲取圖片角度 1:0°正常 3:180° 6:順時針90° 8: 逆時針90°
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
//瓦片canvas
let tCanvas = document.createElement("canvas");
let tctx = tCanvas.getContext("2d");
let width = img.width;
let height = img.height;
// 如果圖片大於四百萬像素,計算壓縮比並將大小壓至400萬以下
let ratio;
if ((ratio = (width * height) / 4000000) > 1) {
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
// 鋪底色
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
//如果圖片像素大於100萬則使用瓦片繪製
let count;
if ((count = (width * height) / 1000000) > 1) {
count = ~~(Math.sqrt(count) + 1); //計算要分成多少塊瓦片
// 計算每塊瓦片的寬和高
let nw = ~~(width / count);
let nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (let i = 0; i < count; i++) {
for (let j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, 0, 0, width, height)
}
if (Orientation && Orientation !== 1) {
switch (Orientation) {
case 6:
canvas.width = height
canvas.height = width
ctx.rotate(Math.PI / 2)
ctx.drawImage(img, 0, -height, width, height)
console.log('旋轉');
break
case 3:
ctx.rotate(Math.PI)
ctx.drawImage(img, -width, -height, width, height)
break
case 8:
canvas.width = height
canvas.height = width
ctx.rotate(3 * Math.PI / 2)
ctx.drawImage(img, -width, 0, width, height)
break
}
}
//進行最小壓縮
let ndata = canvas.toDataURL("image/jpeg", 0.1);
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
//將base64轉換爲文件
let arr = ndata.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], fileName, {type:mime});
},
getExif(file) {
// 獲取圖片旋轉方向
let Orientation = '';
Exif.getData(file, function() {
Orientation = Exif.getTag(this, 'Orientation');
});
return Orientation;
},