微信小程序上传图片压缩
2022-08-02 本文已影响0人
xsmile21
上传图片时图片过大,接口请求速度会很慢,利用canvas对图片进行压缩
wxml文件:
<canvas canvas-id="canvas" style="width:{{cWidth}}px;height:{{cHeight}}px;position: absolute;left:-1000px;top:-1000px;"></canvas>
js文件:
data: {
cWidth: 0,
cHeight: 0
}
wx.chooseImage({
count: 1,
sizeType: ['compressed'], // 官方压缩设置
success: function(res) {
console.log(res);
wx.getImageInfo({
src: res.tempFilePaths[0],
success: function(res) {
var ratio = 2;
// 图片原始长宽
var canvasWidth = res.width;
var canvasHeight = res.height;
// 保证宽高在400以内
while (canvasWidth > 400 || canvasHeight > 400){
canvasWidth = Math.trunc(res.width / ratio);
canvasHeight = Math.trunc(res.height / ratio);
ratio++;
}
_this.setData({
cWidth: canvasWidth,
cHeight: canvasHeight
})
var ctx = wx.createCanvasContext('canvas');
ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight);
ctx.draw(false, setTimeout(function(){
wx.canvasToTempFilePath({
canvasId: 'canvas',
destWidth: canvasWidth,
destHeight: canvasHeight,
success: function (res) {
// 最终图片路径
console.log(res.tempFilePath);
},
fail: function (res) {
console.log(res.errMsg);
}
})
},100))
}
})
}
})