当前位置:网站首页>Wechat applet camera compressed image is Base64

Wechat applet camera compressed image is Base64

2022-06-23 02:21:00 Tanguangjian

Wechat applet can easily call the hardware of the device across models , for example : camera 、 horn 、 Bluetooth, etc . Studied Bluetooth before , However, due to the limited interface and few documents at that time, there was no deep dive ; But this is a direction , If you have a chance to do it again . This time let's talk about cameras , The function is to take pictures through the camera and then compress the pictures Base64 Upload to server .

First step : Turn on the camera and instant display

First of all, the display must be in WXML File specifies an area :

<!--  Camera components , Put it in UI The bottom layer shows the camera content  -->
<camera frame-size="medium"
        bindinitdone="onCameraInit"
        mode="normal"
        device-position="back"
        resolution="high"
        flash="off"/>
<!-- canvas Components , For image compression , The position is outside the screen , invisible  -->
<canvas type="2d"
        id="capture"
        style="width: 1px; height: 1px;"/>

And then in JS Call the camera to play , Monitor the camera .

const query = wx.createSelectorQuery();
query.select('#capture')
    .fields({node: true})
    .exec((res) => {
        const canvas = res[0].node;
        // Set up canvas The internal dimensions are 480*640,frame-size="medium" Most of the camera frames are 480*640
        canvas.width = 480;
        canvas.height = 640;
        this.canvas = canvas;
    });

let cameraContext = wx.createCameraContext();
let listener = cameraContext.onCameraFrame(frame => {
    if (!this.canvas) return;
    let canvas = this.canvas;
    // If the dimensions do not match , Just modify canvas Size to fit the camera frame 
    if (canvas.width !== frame.width || canvas.height !== frame.height) {
        canvas.width = frame.width;
        canvas.height = frame.height;
    }

    //TODO  Save here frame object , In order to compress the picture in the next step when necessary 、 launch CRS request . Not in onCameraFrame Handle directly in callback .
});
listener.start();

The second step : Get the image and compress it

Here you can search upng.js This third party js, Of course, this depends on pako package , We don't have to this time ..

let context = this.canvas.getContext('2d');
let ctxImageData = context.createImageData(frame.width, frame.height);
ctxImageData.data.set(new Uint8ClampedArray(frame.data)); // Copy camera frame contents to imageData
context.putImageData(ctxImageData, 0, 0); // take imageData Draw to canvas On 
let dataUrl = this.canvas.toDataURL("image/jpeg", 0.7); // Use toDataURL Method to compress the camera frame into JPEG, quality 70%
let base64 = dataUrl.substr(23); // Remove dataURL head , Leave the contents of the document base64

The third step : Data initiation request

const params = {
    image: base64,
    notracking: "true",
    appId: " Cloud recognition library  CRS AppId",
};

// https:// Cloud recognition library Client-end URL>/search  When you don't know your goal ,HTTP Status code for 404.
return new Promise((resolve, reject) => {
    wx.request({
        url: "URL",
        method: 'post',
        data: params,
        header: {
            'Authorization': " Use APIKey+APISecret Generated Token",
            'content-type': 'application/json'
        },
        success: res => resolve(res.data), // See the following for the treatment method 
        fail: err => reject(err),
    });
});

Of course

  wx.request({
          url: "URL",
          method: 'POST',
          header: {
            'content-type': 'application/json' //  The default value is 
          },
          data: {
            "image": base64,
            "top_num": 1,
            "threshold": 0.01
          },
          success: function (res) {        
            
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            //  that.setData({ sendload: false });
          }
        })

In this way, the pictures obtained by the simple camera are compressed and converted into BASE64 And upload . Of course, the code is only the core function code , The peripheral functions can be debugged by yourself .

原网站

版权声明
本文为[Tanguangjian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202081658442590.html