微信小程序自带的图像压缩函数并不好用,这里利用画布来进行图像压缩。
ps:wx.createCanvasContext() 已停止维护,故使用 NodesRef.context 来替代,写法如下:
wxml:(一定要指定 id 和 type)
<canvas
id="canvas"
type="2d"
style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>
js:
chooseImage() {
//选择图片
wx.pro.chooseImage({
count:1,
sizeType:['original','compressed'],
sourceType:['album','camera'],
}).then((res)=>{
//获取图片路径信息
wx.pro.getImageInfo({
src:res.tempFilePaths[0],
}).then((res)=>{
var ratio = 2;
var canvasWidth = res.width;
var canvasHeight = res.height;
var path = res.path;
//进行图像压缩
while (canvasWidth * canvasHeight >= 65536){
canvasWidth = Math.trunc(res.width / ratio);
canvasHeight = Math.trunc(res.height / ratio);
ratio++;
console.log(canvasHeight,canvasWidth);
}
this.data.cWidth = canvasWidth;
this.data.cHeight = canvasHeight;
//选择画布节点
wx.createSelectorQuery()
.select("#canvas")
.fields({node:true,size:true})
.exec((res)=>{
const cvs= res[0].node;
const ctx = cvs.getContext('2d');
const img = cvs.createImage();
img.src = path;
//绘制图像
ctx.drawImage(img,0,0,canvasWidth,canvasHeight);
//获取图像路径
wx.canvasToTempFilePath({
canvas:cvs
}).then((res)=>{
this.data.filePath = res.tempFilePath;
}).catch((e)=>{
console.log(e);
})
})
})
wx.pro.showToast({
icon:"loading",
title:'正在上传'
})
}).catch((e)=>{
console.log(e);
})
},
最终,压缩的图片路径被存储在 this.data.filePath 中,按需取用。