需求:我这个是有图片的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, // 压缩质量,0.6表示60%
success: (result) => {
// 压缩成功后,将压缩后的图片转换为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]" />
网友评论