This article mainly introduces the image compression function of WeChat applet in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Brother Xiaolong’s WeChat applet is equivalent to 6 in the IE world at the initial stage. Here I will tell you about a pit that I just went through.
Photography API.
wx.chooseImage({ count: 1, // 默认9 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths; } });
In the above, the size type is clearly given. I wanted to save trouble, but it is of no use...
Stop talking nonsense, here. Let’s talk about the differences between IOS and Android and the pitfalls of image compression.
// 点击照相 takePictures:function(){ var that = this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 var tempFilePaths = res.tempFilePaths; that.setData({ attendSuccessImg:tempFilePaths[0] }); // 上传图片 //判断机型 var model = ""; wx.getSystemInfo({ success:function(res){ model= res.model; } }) if(model.indexOf("iPhone") <= 0){ that.uploadFileOpt(that.data.attendSuccessImg); console.log(111111) }else{ drawCanvas(); } // 缩放图片 function drawCanvas(){ const ctx = wx.createCanvasContext('attendCanvasId'); ctx.drawImage(tempFilePaths[0], 0, 0, 94, 96); ctx.draw(); that.prodImageOpt(); } } }); }, // 生成图片 prodImageOpt:function(){ var that = this; wx.canvasToTempFilePath({ canvasId: 'attendCanvasId', success: function success(res) { that.setData({ canvasImgUrl:res.tempFilePath }); // 上传图片 that.uploadFileOpt(that.data.canvasImgUrl); }, complete: function complete(e) { } }); },
After clicking to take a photo, IOS performs image compression function. However, Android is still so large, so during this process, we need to judge the current machine type, and then perform canvas compression.
The above code can be used as soon as you get it, but there is a small part of wxml that needs to be added with a canvas tag.
Make interface calls. I hope everyone has to help.
Related recommendations:
Image compression implementation method in JS
Recommended 10 commonly used image compression upload usage, welcome download!
In-depth analysis of HTML5 image compression upload function
The above is the detailed content of How to implement the image compression function of WeChat applet. For more information, please follow other related articles on the PHP Chinese website!