使用vant uploader組件
<van-uploader v-model="fileList" capture="camera" :max-count="5" upload-icon="plus" :before-read="beforeRead" />
在圖片上傳前壓縮圖片
beforeRead(file) {
return this.compressImg(file);
},
圖片壓縮方法
compressImg(fileObj) {
return new Promise((resolve, reject) => {
let quality = 0.7; //壓縮系數(shù)0-1之間
let reader = new FileReader();
reader.readAsDataURL(fileObj);
reader.onload = function(e) {
let image = new Image(); //新建一個(gè)img標(biāo)簽(不嵌入DOM節(jié)點(diǎn),僅做canvas操作)
image.src = e.target.result; //讓該標(biāo)簽加載base64格式的原圖
image.onload = function() { //圖片加載完畢后再通過(guò)canvas壓縮圖片,否則圖片還沒(méi)加載完就壓縮,結(jié)果圖片是全黑的
let canvas = document.createElement('canvas'), //創(chuàng)建一個(gè)canvas元素
context = canvas.getContext('2d'), //context相當(dāng)于畫筆,里面有各種可以進(jìn)行繪圖的API
imageWidth = image.width / 2, //壓縮后圖片的寬度,這里設(shè)置為縮小一半
imageHeight = image.height / 2, //壓縮后圖片的高度,這里設(shè)置為縮小一半
data = ''; //存儲(chǔ)壓縮后的圖片
canvas.width = imageWidth; //設(shè)置繪圖的寬度
canvas.height = imageHeight; //設(shè)置繪圖的高度
//使用drawImage重新設(shè)置img標(biāo)簽中的圖片大小,實(shí)現(xiàn)壓縮。drawImage方法的參數(shù)可以自行查閱W3C
context.drawImage(image, 0, 0, imageWidth, imageHeight);
//使用toDataURL將canvas上的圖片轉(zhuǎn)換為base64格式
data = canvas.toDataURL('image/jpg', quality);
// 如想確保圖片壓縮到自己想要的尺寸,如要求在50-128kb之間,請(qǐng)加以下語(yǔ)句,quality初始值根據(jù)情況自定
while (data.length / 1024 > 128) {
quality -= 0.01;
data = canvas.toDataURL("image/jpg", quality);
}
// 防止最后一次壓縮低于最低尺寸,只要quality遞減合理,無(wú)需考慮
while (data.length / 1024 < 50) {
quality += 0.001;
data = canvas.toDataURL("image/jpg", quality);
}
canvas.toBlob(function (blob) {
const f = new File([blob], fileObj.name,{type: 'image/jpg'});
resolve(f);
},'image/jpg')
}
}
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。