一 .https://blog.youkuaiyun.com/Superman_peng/article/details/107740407
1.安装模块
npm i image-conversion --save
2.引入imageConversion,进行压缩
const imageConversion = require("image-conversion");
3.实现
1》压缩到指定大小
//把图片文件作为参数传递到方法中
beforeAvatarUpload(file) {
console.log(file)
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJpgOrPng) {
this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
return false;
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
return false;
}
return new Promise((resolve) => {
// 压缩到100KB,这里的100就是要压缩的大小,可自定义
imageConversion.compressAccurately(file, 100).then(res => {
console.log(res)
resolve(res);
});
//compressAccurately有多个参数时传入对象
//imageConversion.compressAccurately(file, {
// size: 1024, //图片大小压缩到1024kb
// width:1280 //宽度压缩到1280
//}).then(res => {
//resolve(res)
//})
})
},
2》按照一定质量倍数进行压缩
以质量为0.6进行压缩
//把图片文件作为参数传递到方法中
beforeAvatarUpload(file) {
console.log(file)
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJpgOrPng) {
this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
return false;
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
return false;
}
return new Promise((resolve) => {
imageConversion.compress(file,0.6).then(res=>{
console.log(res);
resolve(res);
})
}
},
二.压缩后格式是blob格式,formData上传到服务器时需要拼接图片名称,否则会出现所有上传的图片名称都为blob。
这里有个坑,那就是 FormData.append(‘file’, file),如果只有两个参数,(第三个参数是文件名)的情况下,默认fileName=“blob”,这样上次至后台,如果后台未做其他处理的话,就会出现报错的情况,后来就添加了随机文件名,完美解决问题。
image.append("file", file, this.random_string(12) + '.' + this.fileType);
详细如下:
https://www.cnblogs.com/milo-wjh/p/9260276.html