本文主要講解基于 Vue + Vant ,實(shí)現(xiàn)移動(dòng)端圖片選擇,并用 Canvas 壓縮圖片,最后上傳至服務(wù)器。還會(huì)封裝一個(gè)工具類,方便直接調(diào)用。

一、工具類封裝
廢話不多說(shuō)先上代碼,封裝一個(gè) CompressImageUtils 工具類:
**
* 圖片壓縮工具類
* 大高度和大寬度都為 500,如果超出大小將等比例縮放。
*
* 注意可能出現(xiàn)壓縮后比原圖更大的情況,在調(diào)用的地方自己判斷大小并決定上傳壓縮前或壓縮后的圖到服務(wù)器。
*/
// 將base64轉(zhuǎn)換為blob
export function convertBase64UrlToBlob(urlData) {
let arr = urlData.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {type: mime})
}
// 壓縮圖片
export function compressImage(path) {
//大高度
const maxHeight = 500;
//大寬度
const maxWidth = 500;
return new Promise((resolve, reject) => {
let img = new Image();
img.src = path;
img.onload = function () {
const originHeight = img.height;
const originWidth = img.width;
let compressedWidth = img.height;
let compressedHeight = img.width;
if ((originWidth > maxWidth) && (originHeight > maxHeight)) {
// 更寬更高,
if ((originHeight / originWidth) > (maxHeight / maxWidth)) {
// 更加嚴(yán)重的高窄型,確定大高,壓縮寬度
compressedHeight = maxHeight
compressedWidth = maxHeight * (originWidth / originHeight)
} else {
//更加嚴(yán)重的矮寬型, 確定大寬,壓縮高度
compressedWidth = maxWidth
compressedHeight = maxWidth * (originHeight / originWidth)
}
} else if (originWidth > maxWidth && originHeight <= maxHeight) {
// 更寬,但比較矮,以maxWidth作為基準(zhǔn)
compressedWidth = maxWidth
compressedHeight = maxWidth * (originHeight / originWidth)
} else if (originWidth <= maxWidth && originHeight > maxHeight) {
// 比較窄,但很高,取maxHight為基準(zhǔn)
compressedHeight = maxHeight
compressedWidth = maxHeight * (originWidth / originHeight)
} else {
// 符合寬高限制,不做壓縮
}
// 生成canvas
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
canvas.height = compressedHeight;
canvas.width = compressedWidth;
context.clearRect(0, 0, compressedWidth, compressedHeight);
context.drawImage(img, 0, 0, compressedWidth, compressedHeight);
let base64 = canvas.toDataURL('image/*', 0.8);
let blob = convertBase64UrlToBlob(base64);
// 回調(diào)函數(shù)返回blob的值。也可根據(jù)自己的需求返回base64的值
resolve(blob)
}
})
}
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
新聞標(biāo)題:Vue圖片壓縮并上傳至服務(wù)器功能-創(chuàng)新互聯(lián)
文章網(wǎng)址:http://chinadenli.net/article8/cepcop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、網(wǎng)頁(yè)設(shè)計(jì)公司、網(wǎng)站制作、建站公司、定制開(kāi)發(fā)、微信公眾號(hào)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容