当前位置:网站首页>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 base64The 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 .
边栏推荐
- Spark broadcast variables and accumulators (cases attached)
- 1. Mx6u bare metal program (1) - Lighting master
- Mobile communication Overview - Architecture
- what the fuck! If you can't grab it, write it yourself. Use code to realize a Bing Dwen Dwen. It's so beautiful ~!
- Hello
- EDI project cases of customers in medical device industry
- 1. Mx6u bare metal program (2) - Lighting master (imitating 32 register version)
- 9. class and object practice and initialization list
- Arm assembly syntax
- Small knowledge points of asset
猜你喜欢

Performance test -- Jenkins environment construction for 15jmeter performance test

Cut! 39 year old Ali P9 saved 150million

How to make word notes beautiful

Classical questions of function recursion

Dynamic address book in C language (add, delete, modify, check (duplicate), delete, sort and export)

1. Mx6u bare metal program (5) - external interrupt

Analog Electronic Technology

Anaconda creates a new environment encounter pit

Microservice Optimization: internal communication of microservices using grpc

How to design API return codes (error codes)?
随机推荐
[CodeWars] Convert Decimal Degrees to Degrees, Minutes, Seconds
Performance test -- 14 detailed explanation of performance test report and precautions
Branch and loop statements (including goto statements) -part2
Why is BeanUtils not recommended?
Get the structure of the class through reflection, little chestnut
Schedule tasks to periodically restart remote services or restart machines
【CodeWars】 Pete, the baker
//1.9 char character variable operation
【CodeWars】What is between?
Digital circuit logic design
1. Mx6u bare metal program (1) - Lighting master
Cmake configuration error, error configuration process, Preject files may be invalid
Buuctf misc-[actf freshman competition 2020]outline
Information theory and coding
Log a log4j2 vulnerability handling
Circuit analysis (circuit principle)
1. Mx6u startup mode and equipment
"Initial C language" (Part 2)
Use of apicloud AVM framework list component list view and flex layout tutorial
The practice of traffic and data isolation in vivo Reviews