最近有個需求,就是上傳圖檔的時候,圖檔過大,需要壓縮一下圖檔再上傳。
需求雖然很容易了解,但要做到,不是那麼容易的。
這裡涉及到的知識有點多,不多說,本篇部落格有點重要呀!
一、圖檔URL轉Blob(圖檔大小不變)
注意點:圖檔不能跨域!!!
方式一:通過XHR請求擷取
function urlToBlobByXHR(url) {
const xhr = new XMLHttpRequest();
xhr.open("get", url);
xhr.responseType = "blob"; // 設定響應請求格式
xhr.onload = (e) => {
if (e.target.status == 200) {
console.log(e.target.response); // e.target.response傳回的就是Blob。
return e.target.response;// 這樣是不行的
}
else {
console.log("異常");
}
};
xhr.send();
}
urlToBlobByXHR("圖檔URL"); // 調用
我們知道,XHR操作是異步的,隻有在onload方法裡面才能擷取到Blob,相應的業務代碼也要寫到裡面。怎麼能夠做到調用這個方法,直接得到Blob結果呢?
Promise便解決了諸如此類的痛點。
function urlToBlobByXHR(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("get", url);
xhr.responseType = "blob";
xhr.onload = (e) => {
if (e.target.status == 200) {
resolve(e.target.response); // resolve
}
else {
reject("異常"); // reject
}
};
xhr.send();
})
}
async f() {
try {
console.log(await urlToBlobByXHR(this.imgUrl)); // 直接傳回Blob
} catch (e) {
console.log(e);
}
}
f(); // 調用
方式二:通過canvas轉化(圖檔大小會變大很多)
基本原理:就是建立一個canvas元素,然後在裡面将圖檔畫上去,接着利用canvas轉為Blob。
function canvasToBlob(imgUrl) {
return new Promise((resolve, reject) => {
const imgObj = new Image();
imgObj.src = imgUrl;
imgObj.onload = () => {
const canvasObj = document.createElement("canvas");
const ctx = canvasObj.getContext("2d");
canvasObj.width = imgObj.naturalWidth;
canvasObj.height = imgObj.naturalHeight;
ctx.drawImage(imgObj, 0, 0, canvasObj.width, canvasObj.height);
canvasObj.toBlob((blob) => {
resolve(blob);
});
}
})
}
const blobCanvas = await canvasToBlob(imgUrl); // 調用,直接擷取到blob
不過呢,利用canvas轉化,圖檔會變大很多,在canvas上面畫圖檔,期間圖檔分辨率會改變,加上可能還有圖檔解析的原因,會導緻圖檔變大很多。
而且canvas是可以截圖的,不過這一點是人為可以控制的。
二、圖檔壓縮
原理:我們知道在canvas裡面畫圖,canvas相當于圖檔的容器,既然是容器,那便可以控制容器的寬高,相應的改變圖檔的寬高,通過這一點,不就可以縮小圖檔了嗎?
不過要注意的是,縮小圖檔要等比例的縮小,雖然提供的接口裡面支援更改圖檔清晰度,但個人并不建議這麼做,至于原因自己想吧。
版本一:
// imageUrl:圖檔URL,圖檔不能跨域
// maxSize:圖檔最大多少M
// scale:圖檔放大比例
function compressImg1(imageUrl, maxSize = 1, scale = 0.8, imgWidth, imgHeight) {
let maxSizeTemp = maxSize * 1024 * 1024;
return new Promise((resolve, reject) => {
const imageObj = new Image();
imageObj.src = imageUrl;
imageObj.onload = () => {
const canvasObj = document.createElement("canvas");
const ctx = canvasObj.getContext("2d");
if (imgWidth && imgHeight) { // 等比例縮小
canvasObj.width = scale * imgWidth;
canvasObj.height = scale * imgHeight;
}
else {
canvasObj.width = imageObj.naturalWidth;
canvasObj.height = imageObj.naturalHeight;
}
ctx.drawImage(imageObj, 0, 0, canvasObj.width, canvasObj.height);
canvasObj.toBlob((blob) => {
resolve({ blob, canvasObj });
});
}
}).then(({ blob, canvasObj }) => {
if (blob.size / maxSizeTemp < maxSize) {
let file = new File([blob], `test${imageUrl.substring(imageUrl.lastIndexOf("."))}`);
return Promise.resolve({ blob, file });
}
else {
return compressImg1(imageUrl, maxSize, scale, canvasObj.width, canvasObj.height); // 遞歸調用
}
})
}
const { blob } = await compressImg1("圖檔位址"); // 調用
需求是實作了,但用到了遞歸,性能完全由縮小比例跟圖檔大小決定。
圖檔過大的話或者縮小比例大了點,會導緻不斷遞歸,性能低下,這是肯定的。
以上還有兩個耗時的操作:
1、不斷請求圖檔
2、不斷操作DOM
版本二:
有個潛規則,能不用遞歸就不用遞歸。
試想,怎樣一步到位可以把圖檔縮小到需要的大小呢?再深入直接一點,如何得到有效的scale,等比例縮小後就能使圖檔縮小到想要的程度呢?
然後再把以上兩個耗時操作再優化一下,隻需加載一次圖檔。便得到了版本二。
function compressImg2(imageUrl, maxSize = 1, scale = 1) {
let maxSizeTemp = maxSize * 1024 * 1024;
return new Promise((resolve, reject) => {
const imageObj = new Image(); // 隻需加載一次圖檔
imageObj.src = imageUrl;
imageObj.onload = () => {
const canvasObj = document.createElement("canvas"); // 隻需建立一次畫布
const ctx = canvasObj.getContext("2d");
canvasObj.width = imageObj.naturalWidth;
canvasObj.height = imageObj.naturalHeight;
ctx.drawImage(imageObj, 0, 0, canvasObj.width, canvasObj.height);
canvasObj.toBlob((blob1) => {
resolve({ imageObj, blob1, canvasObj, ctx });
});
}
}).then(({ imageObj, blob1, canvasObj, ctx }) => {
if (blob1.size / maxSizeTemp < maxSize) {
let file = new File([blob1], `test${imageUrl.substring(imageUrl.lastIndexOf("."))}`);
return Promise.resolve({ blob: blob1, file });
}
else {
const ratio = Math.round(blob1.size / maxSizeTemp); // 比例
canvasObj.width = (imageObj.naturalWidth / ratio) * scale; // 比例調整
canvasObj.height = (imageObj.naturalHeight / ratio) * scale;
ctx.drawImage(imageObj, 0, 0, canvasObj.width, canvasObj.height);
return new Promise((resolve) => {
canvasObj.toBlob((blob2) => {
let file = new File([blob2], `test${imageUrl.substring(imageUrl.lastIndexOf("."))}`);
resolve({ blob: blob2, file });
});
})
}
})
}
版本三(Promise轉為async await)
我們知道Promise跟asnc await是等價的。
async function compressImg(imageUrl, maxSize = 1, scale = 1) {
let maxSizeTemp = maxSize * 1024 * 1024;
const { imageObj, blob1, canvasObj, ctx } = await new Promise((resolve, reject) => {
const imageObj = new Image();
imageObj.src = imageUrl;
imageObj.onload = () => {
const canvasObj = document.createElement("canvas");
const ctx = canvasObj.getContext("2d");
canvasObj.width = imageObj.naturalWidth;
canvasObj.height = imageObj.naturalHeight;
// console.log(canvasObj);
ctx.drawImage(imageObj, 0, 0, canvasObj.width, canvasObj.height);
canvasObj.toBlob((blob1) => {
// console.log('blob1', blob1);
resolve({ imageObj, blob1, canvasObj, ctx });
});
};
});
if (blob1.size / maxSizeTemp < maxSize) {
let file = new File([blob1], `test${imageUrl.substring(imageUrl.lastIndexOf("."))}`);
return Promise.resolve({ blob: blob1, file });
}
else {
// const ratio = Math.round(Math.sqrt(blob1.size / maxSizeTemp));
const ratio = Math.round(blob1.size / maxSizeTemp);
// console.log('ratio', ratio);
canvasObj.width = (imageObj.naturalWidth / ratio) * scale;
canvasObj.height = (imageObj.naturalHeight / ratio) * scale;
// console.log(canvasObj);
ctx.drawImage(imageObj, 0, 0, canvasObj.width, canvasObj.height);
const { blob: blob2, file } = await new Promise((resolve) => {
canvasObj.toBlob((blob2) => {
// console.log('blob2', blob2);
let file = new File([blob2], `test${imageUrl.substring(imageUrl.lastIndexOf("."))}`);
resolve({ blob: blob2, file });
});
})
return { blob: blob2, file };
}
}
三、詳細講解下Promise
簡單的一個例子
let p = new Promise((resolve) => {
setTimeout(() => {
resolve(123456); // 5秒後輸出123456
}, 5000);
});
p.then((s) => {
console.log(s); // 通過then的參數就可以擷取到結果
});
let s = await p; // async await轉換,簡化then寫法
console.log(s);
其實呢,Promise本質上就是回調函數的使用,而Promise主要是為了解決回調地獄(回調函數嵌套)而出現的,async await寫法主要是為了簡化友善。
咱來模拟一下最簡單的Promise,手寫一個簡單一點的。
// 首先定義一下Promise狀态
const status = {
pending: "pending",
fulfilled: "fulfilled",
rejected: "rejected",
};
不支援異步(先來個簡單的)
function MyPromise(executor) {
const self = this;// this指向
self.promiseStatus = status.pending;
self.promiseValue = undefined;
self.reason = undefined;
function resolve(value) {
if (self.promiseStatus == status.pending) {
self.promiseStatus = status.fulfilled;
self.promiseValue = value;
}
}
function reject(reason) {
if (self.promiseStatus == status.pending) {
self.promiseStatus = status.rejected;
self.reason = reason;
}
}
try {
executor(resolve, reject); // 在這裡比較難以了解,函數resolve作為函數executor的參數,new MyPromise調用的時候,傳的也是個函數。
} catch (e) {
reject(e);
}
}
MyPromise.prototype.then = function (onResolve, onReject) { // 利用原型添加方法
const self = this;
if (self.promiseStatus == status.fulfilled) {
onResolve(self.promiseValue);
}
if (self.promiseStatus == status.rejected) {
onReject(self.reason);
}
};
// 調用
const myPromise = new MyPromise((resolve, reject) => { // MyPromise的參數也是個函數
resolve(123456); // 暫時不支援異步
});
myPromise.then((data) => {
console.log("data", data); // 輸出123456
});
支援異步的
function MyPromise(executor) {
const self = this;
self.promiseStatus = status.pending;
self.promiseValue = undefined;
self.reason = undefined;
self.onResolve = [];
self.onReject = [];
function resolve(value) {
if (self.promiseStatus == status.pending) {
self.promiseStatus = status.fulfilled;
self.promiseValue = value;
self.onResolve.forEach((fn) => fn(value)); //支援異步
}
}
function reject(reason) {
if (self.promiseStatus == status.pending) {
self.promiseStatus = status.rejected;
self.reason = reason;
self.onReject.forEach((fn) => fn(reason)); // //支援異步
}
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
MyPromise.prototype.then = function (onResolve, onReject) {
const self = this;
if (self.promiseStatus == status.fulfilled) {
onResolve(self.promiseValue);
}
if (self.promiseStatus == status.rejected) {
onReject(self.reason);
}
if (self.promiseStatus == status.pending) {
self.onResolve.push(onResolve);
self.onReject.push(onReject);
}
};
// 調用
const myPromise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(123456); // 異步
}, 3000);
});
myPromise.then((data) => {
console.log("data", data); // 輸出123456
});
個人覺得,能明白大緻原理,會用就行了,至于能不能手寫一個Promise并不是很重要的,不斷重複造輪子沒啥意思,
但是呢,了解其大概思路以及實作所用到的思想還是很重要的,對成長的幫助很大。
總結
圖檔壓縮還有待優化,
Promise,大家應該都很熟悉,用的非常多,可真正會用的人并不是太多的。
最後,祝大家中秋快樂!