Principle: To use canvas, draw the picture to canvas, and then transfer the picture to canvas, wechat provides a method wx.canvastotempFilepath (Object Object, Object this), which can specify the quality of the generated picture. Below is a screenshot from the official API:

Quality can specify the quality of the image. The smaller the value of quality is, the more blurred the image is

Note:

Quality Settings only apply to JPG images. Set fileType to "JPG". This may cause images in other formats to become JPG. PNG images with transparent background are exported in this way to canvas with black background. If necessary, canvas needs to set the background color first. Please pay attention to crawling.Copy the code

With this parameter, compression is much easier. Here is the code:

wxml

<view>
  <button bindtap="chooseImage"</button> </view> <! < span style= "max-width: 100%; clear: both; min-height: 1em"display: flex; justify-content: center; flex-direction: column">
  <image mode="widthFix" src="{{imagePath}}"></image>
</view>

<button wx:if="{{imagePath.length>0}}" bindtap="save"</button> <! Canvas for rendering --> <canvas canvas-id='attendCanvasId' class='myCanvas' style='width:{{cWidth}}px; height:{{cHeight}}px; position: fixed; top: -9999px; left: -9999px; '></canvas>
Copy the code

js

Page({/** * the initial data of the Page */ data: {imagePath:' ', quality: 0.2, cWidth: 0, cHeight: 0, timer: null}, /** * lifecycle function --function(options) {}, /** * options to add image events */ chooseImage:function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['compressed'], // Select the original image or compressed imagesourceType: ['album'.'camera'Result => {wx.getimageInfo ({SRC: result.tempfilepaths [0], SUCCESS:function (res) {
            console.log(res.width, res.height)
            that.setData({
              cWidth: res.width,
              cHeight: res.height
            }, () => {
              // setData causes the callback function // after the page has been renderedsetGetCanvasImg (result.tempFilepaths, res.width, res.height, that.data.quality); })}})}, /** * getCanvasImg(tempFilePaths, canvasWidth, canvasHeight, quality) {var that = this; const ctx = wx.createCanvasContext('attendCanvasId');
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
    let pixelRatio = wx.getSystemInfoSync().pixelRatio
    ctx.drawImage(tempFilePaths[0], 0, 0, canvasWidth, canvasHeight);
    ctx.draw(false.function () {
      that.data.timer = setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'attendCanvasId',
          fileType: 'jpg',
          quality: quality,
          destWidth: canvasWidth,
          destHeight: canvasHeight,
          success: function success(res) {
            clearTimeout(that.data.timer)
            that.setData({
              imagePath: res.tempFilePath
            });
          },
          fail: function (e) {
            clearTimeout(that.data.timer)
            wx.showModal({
              title: 'tip', content: JSON.stringify(e), }) } }); }, 500)}); }, /** * save(e) {let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success: function (res) {
        console.log('Picture saved');
      },
      fail: function (res) {
        console.log('Save failed'); }})}})Copy the code

Note:

  1. Note that canvas-id=’attendCanvasId’
  2. The canvas is rendered off-screen, that is, out of the screen, but the elements are still displayed, position: fixed; top: -9999px; left: -9999px; You cannot use display: none; You can’t get canvas elements in this way.

Effect of compression

Wechat developer tools

Below the k

The original image size Compressed size
36.6 Kb 9.28 Kb
55.1 Kb 34.4 Kb
83.7 Kb 14.7 Kb

The k

The original image size Compressed size
229Kb 34.4 Kb
201Kb 109Kb

Mb

The original image size Compressed size
2.99 Mb 158Kb
4.26 Mb 162Kb

Android 9

The original image size Compressed size
1.11 Mb 290Kb
249Kb 107Kb
129Kb 110Kb

ios

The original image size Compressed size
310Kb 169Kb

The larger the picture, the greater the proportion of compression, it is recommended to make a judgment before compression, 100 Kb below the picture, is already very small

The last

The H5 page also provides this method

Like this:

let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
ctx.drawImage(imagePath, 0, 0, w, h);
canvas.toDataURL('image/jpeg', quality);
Copy the code

Need small partners can also study their own ha…

Source code – Welcome star

Thank you

Ok, end, 👏