I remember that the response of Mini Program code is a binary stream. Image can not directly display a binary stream, but can display base64. If you only show a small code of the Mini Program and do not want the backend to return a url, then the backend can convert the binary stream into base64 and return the front end. If the shared image is dynamic and contains a lot of content, it is better to generate and return it on the server.
<image wx:if="{{imageCode}}" @tap="herfCode" class='right' src='{{imageCode}}'/>
the value of direct src = base64 is fine
WeChat Mini Programs code API returns a binary stream. With the help of the front-end js tool, you can change the binary stream to base64 image and display it directly
you can take a look at this blog and test it for yourself.
After the
backend returns base64 data, concatenate the data:image/jpeg;base64,
prefix, and then call the method written in the blog:
reference: import base64src from'.. /.. / utils/base64src.js'
call:
base64src('data:image/jpeg;base64,' + res.data).then(path => {
// context.drawImage(path, ......)
}).catch(res => {
// error
})
The basic
idea of
is to first save the base64
data locally, and then draw it on canvas
using the local picture path.
base64src.js:
const fsm = wx.getFileSystemManager();
const FILE_BASE_NAME = 'tmp_base64src';
const base64src = function(base64data) {
return new Promise((resolve, reject) => {
const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
if (!format) {
reject(new Error('ERROR_BASE64SRC_PARSE'));
}
const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
const buffer = wx.base64ToArrayBuffer(bodyData);
fsm.writeFile({
filePath,
data: buffer,
encoding: 'binary',
success() {
resolve(filePath);
},
fail() {
reject(new Error('ERROR_BASE64SRC_WRITE'));
},
});
});
};
export default base64src;
WeChat Mini Programs base64 picture canvas canvas drawImage
Mini Program's canvas does not seem to support drawing network pictures and base64 pictures, so you can only download the pictures locally before using
.