需求:我這個是有圖片的src地址,但是圖片太大摆尝,加載慢温艇,所以需要壓縮,市面上的好多需求都是在上傳的時候進行壓縮堕汞,我這個案例是對src進行壓縮成base64然后加載
1.安裝compressorjs
npm install compressorjs
2.引用
import Compressor from "compressorjs";
3.js代碼
//imageMap :{id:base64url} 是一個對象勺爱,如果壓縮就用小圖地址,如果不壓縮就用大圖地址
//獲取壓縮后圖片的base64地址讯检,并且組成一個新對象
//imgList:[ { FileId:'',src:'' } ]
async getImageMap() {
let temp = {};
try {
for (let i = 0; i < this.imgList.length; i++) {
let item = this.source[i];
let bigSrc = item.src;
let smallSrc = await this.pathToBlob(bigSrc);
if (this.isCompressor) {
temp[item.FileId] = smallSrc;
} else {
temp[item.FileId] = bigSrc;
}
}
} catch (e) {}
this.imageMap = temp;
},
//圖片路徑變blob
pathToBlob(path) {
return new Promise((resolve, reject) => {
fetch(path)
.then((response) => {
return response.blob();
})
.then((blob) => {
this.handleImageCompressor(blob)
.then((res) => {
resolve(res);
})
.catch((e) => {
reject(e);
});
});
});
},
//圖片壓縮
handleImageCompressor(blob) {
return new Promise((resolve, reject) => {
const file = new File([blob], "圖片.jpg", { type: "image/jpeg" });
new Compressor(file, {
quality: 0.3, // 壓縮質(zhì)量琐鲁,0.6表示60%
success: (result) => {
// 壓縮成功后,將壓縮后的圖片轉(zhuǎn)換為base64或blob
const reader = new FileReader();
reader.onload = (e) => {
resolve(e.target.result);
};
reader.readAsDataURL(result);
},
error: (e) => {
reject(e);
},
});
});
},
4.html使用
<img :src="imageMap[FileId]" />