Function is divided into two parts: display and submission
In the first phase, users preview images and submit them directly to the background. However, it is found that if the picture is too large, it needs to be processed two times, and the corresponding speed of the interface will be reduced. So compress the picture.
Compression principle: after selecting a picture, use the drawImage method of canvas to redefine the size of the picture, and then use the canvas to tempfilepath method to download the reduced picture.
// Hiding canvas with absolute positioning
<canvas canvas-id="photo_canvas" style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position: absolute;left:-300px;top:-300px;"></canvas>
wx.chooseImage({
count: 1,
sizeType: ['compressed'],
success: function (photo) {
wx.getImageInfo({
src: photo.tempFilePaths[0],
success: function(res){
var ctx = wx.createCanvasContext('photo_canvas');
var ratio = 2;
var canvasWidth = res.width
var canvasHeight = res.height;
// Ensure that the width and height are within 200
while (canvasWidth > 200 || canvasHeight > 200){
//Proportion rounding
canvasWidth = Math.trunc(res.width / ratio)
canvasHeight = Math.trunc(res.height / ratio)
ratio++;
}
_this.setData({
canvasWidth: canvasWidth,
canvasHeight: canvasHeight
})//Set canvas size
ctx.drawImage(photo.tempFilePaths[0], 0, 0, canvasWidth, canvasHeight)
ctx.draw()
//Download canvas pictures
setTimeout(function(){
wx.canvasToTempFilePath({
canvasId: 'photo_canvas',
success: function (res) {
console.log(res.tempFilePath)
},
fail: function (error) {
console.log(error)
}
})
},100)
},
fail: function(error){
console.log(error)
}
})
},
error: function (res) {
console.log(res);
}
})