Wechat applet uses cloud function to obtain applet code (two-dimensional code) to convert buffer stream into picture

Recently, after completing the design, there is a demand to obtain the applet code and draw the sharing poster. Because the business scenario with a large number of applet codes is required, the back-end generation can only be used to return to the front-end call or cloud development call.

Two ways to generate applet code

HTTPS call

The back-end generation is required to return to the front-end. This method will not be described in detail in this article

Cloud function call

Idea:

Applet side request -- > cloud function API  --> Return the buffer of the picture -- > convert the buffer into a picture

1. Create a new cloud function

stay   Right click the cloudfunction directory to create a new Node.js cloud function   getQRCode

Permissions need to be specified separately to generate applet code. stay   getQRCode directory NEW   config.json  , Write the following in it:  

{
  "permissions": {
    "openapi": [
      "wxacode.getUnlimited"
    ]
  }
}

  There are three ways to obtain applet code, and only the interface getUnlimited is used here

2. js part of cloud function getQRCode

Direct paste code

// Cloud function entry file
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async (event, context) => {
  try {
    const result = await cloud.openapi.wxacode.getUnlimited({
      scene: event.scene, //However, the new version cannot use path to pass parameter param
      width: 300
    })
    console.log(result)
    return result
  } catch (err) {
    console.log(err)
    return err
  }
}

Direct call, less access than server call_ Token parameter

The return value is a binary buffer stream. The image content can be displayed by converting the buffer

3. Three methods of converting buffer stream into picture

3.1 directly convert buffer to Base64

console.log('Cloud function call succeeded. Return value:', res);
let bufferImg = "data:image/png;base64," + wx.arrayBufferToBase64(res.result.buffer);
self.setData({
    imgUrl: bufferImg
});

The method used here is wx.arrayBufferToBase64(buffer) conversion. After adding the base64 header, it can be used

  • advantage:   Convenient and simple
  • determine:   Burn after reading and cannot be saved. Individual scenes may need to be cached or spliced canvas posters

3.2 directly upload Buffer to cloud storage in cloud function

await cloud.uploadFile({
    cloudPath: 'test/' + event.userInfo.openId  + '.jpg', //Here, if you can repeat, use openId. If you can't repeat, use openId 
    fileContent: result.buffer, //Processing buffer binary data
    success: res => {
        // File address
        console.log(res.fileID)
    },
    fail: err =>{
        console.log(err)
    }
})


Upload the generated applet code to the built-in cloud storage for long-term permanent storage

  • advantage:   For long-term storage, it is appropriate to generate a scene for repeated use
  • Disadvantages:   If the generation volume is large, it will occupy limited cloud storage resources

3.3 convert and save pictures locally on the mobile phone

let { buffer } = res.result;
const wxFile = wx.getFileSystemManager();
const filePath = wx.env.USER_DATA_PATH + '/test.jpg';
//Write the picture locally
wxFile.writeFile({
    filePath,
    encoding: "binary",
    data: buffer,
    success: res => {
        console.log(res);  //writeFile:ok
        self.setData({
            imgUrl: filePath
        });
    }
})

The method used here is wx.getFileSystemManager(), which converts the image buffer and saves a local address~

  • advantage:   Generate the entity address. Sometimes the picture is too large, and some strange bugs will appear in base64
  • Disadvantages:   time consuming

  4. Specific page part

Page({
    data: {
        imgUrl: "" //Picture address
    },
    getWxacode() {
        wx.cloud.init();
        let self = this;
        wx.showLoading({
            title: 'Request cloud function'
        })
        // Call cloud function to get content
        wx.cloud.callFunction({
            name: 'getQRCode',
            data: {
                scene: "id=666"
            },
            success: res => {
                console.log('Cloud function call succeeded', res);
                self.setData({
                    imgUrl: res.result.fileID
                });
            },
            fail: err => {
                console.error('Cloud function call failed', err)
            }
        })
    },
})

Finally, the scheme of uploading buffer to cloud storage is adopted

Keywords: Javascript Front-end Mini Program

Added by Fira on Mon, 06 Dec 2021 21:08:18 +0200