項目中涉及上傳圖片,如果大體積的一般都需要壓縮,這里我使用image-conversion來壓縮
其實(shí)在npm中使用已經(jīng)說得很明白了,我這里記錄一下跟element ui上傳組件配合使用文章來源:http://www.zghlxwxcb.cn/news/detail-812050.html
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"
>點(diǎn)擊上傳</el-button
>
<div slot="tip" class="el-upload__tip">
只能上傳jpg/jpeg/png文件,
</div>
<div slot="tip" class="el-upload__tip">且不超過30Mb</div>
</el-upload>
上傳前方法中處理壓縮邏輯,壓縮質(zhì)量參數(shù),我單獨(dú)封裝了文章來源地址http://www.zghlxwxcb.cn/news/detail-812050.html
import * as imageConversion from 'image-conversion';
//壓縮質(zhì)量
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;
}
//壓縮質(zhì)量
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;
});
}
},
這樣上傳圖片時壓縮就可以了,大家可以根據(jù)項目壓縮質(zhì)量需求來調(diào)整壓縮參數(shù)
到了這里,關(guān)于vue2上傳圖片image-conversion壓縮的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!