- Use the network request that comes with the applets
- Get the image base64 from canvas
- Get globally unique file manager to read local file content
wxml
<button type="primary" bindtap="btnChooseImage">Copy the code
js
async btnChooseImage() {
wx.chooseImage({
count: 1.sizeType: ['original'.'compressed'].sourceType: ['album'.'camera'].success: (res) = > {
const tempFilePaths = res.tempFilePaths;
tempFilePaths.forEach(val= > {
// Method 1 uses the network request that comes with the applet
this.getImageTobase64_url(val);
Method 2 canvas gets the image base64
this.getImageBase64_canvas(val);
// Get globally unique file manager to read local file contents
this.getImageBase64_readFile(val); }); }})}Copy the code
1. Use the network request provided by the applets
async getImageTobase64_url(tempFilePath) {
const base64 = await new Promise(resolve= > {
wx.request({
url: tempFilePath,
responseType: 'arraybuffer'.// Key parameter to set the returned data format to arrayBuffer
success: res= > {
// Convert arrayBuffer to base64
let data = wx.arrayBufferToBase64(res.data);
return resolve(('data:image/jpeg; base64,'+ data)); }}); });return base64;
}
Copy the code
2. Use Canvas to obtain image Base64
wxnl
<canvas id="myCanvas" type="2d" hidden="true"></canvas>
Copy the code
js
// js
// Use canvas to get the image base64
async getImageBase64_canvas(tempFilePath) {
const {
width,
height
} = await wx.getImageInfo({
src: tempFilePath
});
const base64 = await new Promise(resolve= > {
const query = wx.createSelectorQuery();
query.select("#myCanvas").fields({
node: true./ / for the node
}).exec(res= > {
let {
node: canvas
} = res[0];
let ctx = canvas.getContext('2d');
let image = canvas.createImage();
image.src = tempFilePath;
image.onload = () = > {
ctx.drawImage(image, 0.0, width, height);
resolve(canvas.toDataURL())
}
});
});
return base64;
}
Copy the code
3. Obtain a globally unique file manager to read local file contents
async getImageBase64_readFile(tempFilePath) {
const base64 = await new Promise(resolve= > {
// Get globally unique file manager
wx.getFileSystemManager().readFile({ // Read local file contents
filePath: tempFilePath, // File path
encoding: 'base64'.// Return the format
success: ({ data }) = > {
return resolve('data:image/png; base64,'+ data); }}); });return base64;
}
Copy the code
Conclusion:
Recommend to use for globally unique file manager Read a local file content Note: base libraries to be greater than or equal to 1.9.9 blog: blog.csdn.net/caozhanp/ar…