compressImage 說明
文檔平臺差異說明已標出:官網(wǎng)提供的api
uni.compressImage
除了H5
平臺,其余平臺都支持,所以我們利用條件編譯,然后單獨處理一下H5的圖片壓縮即可。
utils.js
里面封裝一下該方法,方便調(diào)用文章來源:http://www.zghlxwxcb.cn/news/detail-545740.html
/**
* 圖片壓縮
*/
export const imageCompress = (url) => {
return new Promise((resolve, reject) => {
// #ifndef H5
// 條件編譯一下,除了H5平臺,都可以使用uni 自帶的圖片壓縮api處理
uni.compressImage({
src: url,
quality: 80, // 壓縮質(zhì)量,范圍0~100,數(shù)值越小,質(zhì)量越低,壓縮率越高(僅對jpg有效)
success: async res => {
console.log('app-----imgCompress', res.tempFilePath)
resolve(res.tempFilePath)
}
})
// #endif
// #ifdef H5
const img = new Image()
img.src = url
let files = {};
img.onload = async () => {
const canvas = document.createElement('canvas') // 創(chuàng)建Canvas對象(畫布)
const context = canvas.getContext('2d')
// 默認按比例壓縮
let cw = img.width
let ch = img.height
let w = img.width
let h = img.height
canvas.width = w
canvas.height = h
if (cw > 600 && cw > ch) {
w = 600
h = (600 * ch) / cw
canvas.width = w
canvas.height = h
}
if (ch > 600 && ch > cw) {
h = 600
w = (600 * cw) / ch
canvas.width = w
canvas.height = h
}
// 生成canvas
let base64 // 創(chuàng)建屬性節(jié)點
context.clearRect(0, 0, 0, w, h)
context.drawImage(img, 0, 0, w, h)
base64 = canvas.toDataURL()
resolve(base64)
}
// #endif
})
}
封裝的這個方法,只是將圖片地址返回了,也可以根據(jù)具體的實際場景返回不同的數(shù)據(jù)文章來源地址http://www.zghlxwxcb.cn/news/detail-545740.html
到了這里,關(guān)于uniapp 之 多端實現(xiàn)圖片壓縮(含H5實現(xiàn))的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!