前言
小程序上傳圖片,或者拍照上傳圖片,并附帶兼容H5上傳圖片方法,壓縮圖片。
一、支持相冊(cè)選擇和拍照
支持選擇相冊(cè)和拍照,可以使用uniapp提供的api,當(dāng)然也可以自己去封裝自己想要的樣式,我這里直接是使用了uni的方法。uni.chooseImage
配置sourceType: ['album', 'camera']
openSelectImage() {
let tempList = []
uni.chooseImage({
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
if (res.tempFilePaths?.length > 0) {
tempList = res.tempFilePaths
// #ifdef MP
this.recursionCompressMP(tempList, (e) => {
console.log('壓縮后結(jié)果-----', e)
})
// #endif
// #ifdef H5
this.recursionCompressH5(tempList, (e) => {
console.log('壓縮后結(jié)果-----', e)
})
// #endif
}
},
fail: (err) => {
console.log("err: ------", err);
}
})
}
// 微信
async recursionCompressMP(urlList, callback) {
let imgCompressList = []
let imageSize = 0
for (let itemUrl of urlList) {
const result = await this.jumpImageCompress(itemUrl)
if (result?.size < 150000) {
this.tempImageList.push(itemUrl)
continue
}
await this.getUserImageCompress(itemUrl, callback, result?.size)
}
},
壓縮圖片主要用canvas提供的api
1、uni.createCanvasContext 創(chuàng)建 canvas 繪圖上下文。
2、CanvasContext.drawImage 繪制圖像到畫(huà)布。
3、CanvasContext.draw將之前在繪圖上下文中的描述(路徑、變形、樣式)畫(huà)到 canvas 中。
4、當(dāng)canvas繪制完成后,將canvas導(dǎo)出成為圖片,把當(dāng)前畫(huà)布指定區(qū)域的內(nèi)容導(dǎo)出生成指定大小的圖片,并返回文件路徑。uni.canvasToTempFilePath
//微信壓縮圖片
getUserImageCompress(itemUrl, callback, size){
let that = this;
return new Promise ((resolve, reject)=>{
uni.getImageInfo({
src: itemUrl,
success: (res) => {
//獲取設(shè)備像素比,不獲取最后圖片展示有問(wèn)題
uni.getSystemInfo({
success: function(info) {
let ratio = 2;
let canvasWidth = res.width //圖片原始長(zhǎng)寬
let canvasHeight = res.height
let compressWidth = res.width
let quality = 0.1
compressWidth = res.width - 120
canvasHeight = res.height - 120
while (canvasWidth > compressWidth || canvasHeight > canvasHeight) { // 保證寬高在400以內(nèi)
canvasWidth = Math.trunc(res.width / ratio)
canvasHeight = Math.trunc(res.height / ratio)
ratio++;
}
that.canvasWidth = canvasWidth
that.canvasHeight = canvasHeight
let ctx = uni.createCanvasContext('mycanvas')
ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
ctx.draw(false, setTimeout(() => {
uni.canvasToTempFilePath({
canvasId: 'mycanvas',
destWidth: canvasWidth,
destHeight: canvasHeight,
fileType: 'jpg',
quality: quality,
success: function(res1) {
callback && callback(res1.tempFilePath) //拿到圖片壓縮后的臨時(shí)路徑
uni.getFileInfo({
filePath: res1.tempFilePath,
success: (ress) => {
console.log('壓縮之后----',ress) //返回圖片尺寸
callback && callback(res1.tempFilePath)
console.log('添加數(shù)據(jù)----', that.tempImageList)
resolve(res1.tempFilePath)
that.tempImageList.push(res1.tempFilePath)
}
})
},
fail: function(res) {
console.log('canvas錯(cuò)誤---',res.errMsg)
}
})
}, 100)) //留一定的時(shí)間繪制canvas
}
})
},
fail: (e) => {
console.log('錯(cuò)誤----', e)
}
})
})
},
利用返回的圖片大小去控制壓縮的比例,重復(fù)執(zhí)行壓縮函數(shù)。
//返回圖片大小
jumpImageCompress (itemUrl) {
return new Promise((resolve, reject)=>{
uni.getFileInfo({
filePath: itemUrl,
success: (res) => {
console.log('壓縮之前圖片大小----',res) //返回圖片尺寸
resolve(res)
},
fail: (err) =>{
reject(err)
}
})
})
},
//h5
recursionCompressH5(url, callback) {
if (typeof url === 'string') {
this.getUserImageCompressH5(url,callback)
} else if (typeof url === 'object') {
for (let itemImg of url) {
this.getUserImageCompressH5(itemImg,callback)
}
}
},
Tips:因?yàn)镠5端 Canvas 內(nèi)繪制的圖像需要支持跨域訪問(wèn)才能成功。所以h5端uni.canvasToTempFilePath會(huì)返回為空,所以需要使用toBlob轉(zhuǎn)為文件,再利用createObjectURL轉(zhuǎn)為url,這樣就可以獲取到圖片信息。控制壓縮比例。
// h5壓縮圖片
getUserImageCompressH5 (imgUrl,callback) {
let that = this;
return new Promise((resolve, reject)=>{
uni.getImageInfo({
src: imgUrl,
success(res) {
let canvasWidth = res.width; //圖片原始長(zhǎng)寬
let canvasHeight = res.height;
let img = new Image();
img.src = res.path;
console.log(5435435353)
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = canvasWidth / 2;
canvas.height = canvasHeight / 2;
ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
canvas.toBlob(function(fileSrc) {
let imgSrc = window.URL.createObjectURL(fileSrc);
uni.getFileInfo({
filePath: imgSrc,
success: (resFileInfo) => {
if (resFileInfo.size > 150000) {
//壓縮后大于1M就繼續(xù)壓縮
that.recursionCompressH5(imgSrc, callback);
return;
} else {
callback && callback(imgSrc)
resolve(imgSrc)
that.tempImageList.push(imgSrc)
}
},
});
});
}
});
})
},
二、刪除圖片
刪除功能很簡(jiǎn)單,直接使用數(shù)組方的刪除方法splice
就可以了。
deleteSelectImg(index) {
this.tempImageList.splice(index, 1)
},
三、效果圖
至于頁(yè)面ui結(jié)構(gòu),這里就不粘貼了,可以根據(jù)自己實(shí)際需求去實(shí)現(xiàn)。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-551240.html
存在問(wèn)題
在控制壓縮比例的地方,還有一些缺陷,并沒(méi)有很完美的解決壓縮指定大小圖片問(wèn)題。
如有問(wèn)題歡迎指出…文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-551240.html
到了這里,關(guān)于uniapp實(shí)現(xiàn)小程序打開(kāi)相冊(cè)或拍照上傳圖片附贈(zèng)兼容H5方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!