Upload and compress pictures in applet

Keywords: Javascript

To upload an image to an applet, you need to know the values of its attributes. You can find the details in https://developers.weixin.qq.com/miniprogram/dev/api/media-picture.html

Today, I'm going to talk about how to upload the image and compress it. Let's know the following property values

 

First, let's look at the next page display (click upload picture, choose from the album, and click upload again after uploading the picture)

Come on, come on code

wxml code

<button bindtap='chooseImageTap'>Upload pictures</button>
<button bindtap='saveImage'>Preservation</button>
<canvas style="width: 300px; height: 200px;" canvas-id="myCanvas"></canvas>

Of course, the most important is js code

var app = getApp()
Page({
  data: {
    logo: null,
  
pics:[]
  },
 chooseImageTap: function () {
    let _this = this;
    wx.showActionSheet({
      itemList: ['Choose from album', 'Photograph'],//Is the array shown below a photo or something
      itemColor: "#f7982a",//Display text color
      success: function (res) {
        if (!res.cancel) {//Select judgement
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera')
          }
        }
      }
    })

  },
 // Draw picture to canvas upper
  chooseWxImage: function (type) {
   const ctx = wx.createCanvasContext('myCanvas')//canvas
    var that = this;
    wx.chooseImage({//Upload picture event
      count: 9,//Number
      sizeType: ['original', 'compressed'],//original Original picture, compressed Compressed graph, both of which are available by default
      sourceType: ['album', 'camera'], //album Select a picture from the album, camera Use camera, both are available by default
      success: function (res) {
        console.log(res)
        ctx.drawImage(res.tempFilePaths[0], 0, 0, 100, 100)//First selected successfully. The next four values are left,top,width,height,To control the position and size of pictures on the canvas
        ctx.draw()
      }
    })
    },
saveImage: function () {//Here's how to trigger image upload
    var pics = this.data.pics;
    app.uploadimg({
      url: 'https://........',//Here is the interface for uploading your pictures
      path: pics//Here is the address array of the selected picture
    });
  },

 

My personal understanding is like this, but there may be some small mistakes. It's only for your reference. It's not suitable for direct use. Of course, upload the picture to the canvas and get the address of the picture. There's no problem here. It's possible to save the picture finally. It's better to learn more from others. Please correct it

Posted by drorgo on Tue, 31 Dec 2019 05:12:28 -0800