项目中涉及上传图片,如果大体积的一般都需要压缩,这里我使用image-conversion来压缩
其实在npm中使用已经说得很明白了,我这里记录一下跟element ui上传组件配合使用
1、安装image-conversion
npm i image-conversion --save
2、引入使用
2.1、这里配合element ui的上传组件配合使用
<el-upload
class="upload-demo"
style="
display: inline-block;
margin-left: 3%;
vertical-align: top;
"
enctype="multipart/form-data"
:action="baseUrl"
:headers="headers"
name="file"
:data="loadData"
:before-upload="beforeUpload"
:on-success="uploadSuccess"
list-type="picture"
:show-file-list="showFileList"
>
<el-button
size="small"
style="
width: 90px;
backgoound: white;
border: 1px solid rgba(73, 128, 255, 1);
color: rgba(73, 128, 255, 1);
"
class="upload-btn"
>点击上传</el-button
>
<div slot="tip" class="el-upload__tip">
只能上传jpg/jpeg/png文件,
</div>
<div slot="tip" class="el-upload__tip">且不超过30Mb</div>
</el-upload>
上传前方法中处理压缩逻辑,压缩质量参数,我单独封装了
import * as imageConversion from 'image-conversion';
//压缩质量
export function getCompressionQuality(isLtSize,imgType) {
if (isLtSize < 3) {
return 0.93;
} else if (isLtSize >= 3 && isLtSize < 5) {
return 0.90;
} else if (isLtSize >= 5 && isLtSize < 10) {
return 0.80;
} else if (isLtSize >= 10 && isLtSize < 20) {
return 0.70;
} else if (isLtSize >= 20 && isLtSize < 30) {
return 0.60;
}
return 0.90;
}
//压缩逻辑
export function compressImage(file, quality) {
return new Promise((resolve, reject) => {
imageConversion.compress(file, quality)
.then((res) => {
resolve(res);
console.log('压缩后体积', res.size / (1024 * 1024));
})
.catch((error) => {
reject(error);
});
});
}
import { getCompressionQuality, compressImage } from '@/utils/compressionUtils.js';
beforeUploadLoad(file) {
return this.processImage(this, file, this.loadData, false);
},
//上传图片前压缩图片
processImage(that, file, uploadData, isUnload) {
const imgType = file.type.toUpperCase();
const isLt30M = file.size / 1024 / 1024 < 30;
const isLt2M = file.size / 1024 / 1024 < 2;
const isLtSize = file.size / 1024 / 1024;
console.log('压缩前图片size', file.size / 1024 / 1024);
uploadData.isCompressed = 0
if (
imgType !== "IMAGE/JPG" &&
imgType !== "IMAGE/JPEG" &&
imgType !== "IMAGE/PNG"
) {
that.$message.error("请上传正确格式的图片");
return false;
}
if (!isLt30M) {
that.$message.error("上传的图片不能超过30Mb");
return false;
}
//压缩质量
const quality = getCompressionQuality(isLtSize,imgType);
//大于2M走压缩逻辑
if (!isLt2M) {
console.log('quality', quality);
return compressImage(file, quality)
.then(compressedFile => {
return compressedFile;
})
.catch(err => {
console.error('Image compression error:', err);
return file;
});
}
},