Home > Article > WeChat Applet > How to view base64 images in the mini program
How to view base64 images in the mini program? The following article will introduce to you how to preview base64 images in the WeChat applet. I hope it will be helpful to you!
1. The image passed from the background is in base64 format. To display it, use ["data:image/PNG;base64," data
]. can be displayed normally. Then when calling the WeChat API interface previewImage, there are many problems, such as:
2. After inquiry, I found the official answer. WeChat official means that you need to use the url address and the base64 format is not supported. The following is WeChat’s official answer:
wx.previewImage API Previewing base64 images causes WeChat to crash? | WeChat Open Community (qq.com )
https://developers.weixin.qq.com/community/develop/doc/00088c9e44c3d880597ab22b15bc00?highLine=wx.previewImage base64
Idea: First save base64 as a temporary file locally, then preview it, delete the temporary file at the end of the preview
// 获取应用实例 const app = getApp() Page({ data: { //base64数据,由后台传过来 base64: '', //本机的临时文件路径 localImgUrl: '' }, onShow: function() { // 在这里删除临时文件 var localImgUrl = this.data.localImgUrl; if(localImgUrl) { var fs = wx.getFileSystemManager(); fs.unlinkSync(localImgUrl); fs.closeSync(); } }, //预览图片 onPreviewImage() { var base64 = "data:image/PNG;base64," + this.data.base64; var imgPath = wx.env.USER_DATA_PATH + '/e-invoice' + Date.parse(new Date()) + '.png'; var imageData = base64.replace(/^data:image\/\w+;base64,/, ""); var fs = wx.getFileSystemManager(); fs.writeFileSync(imgPath, imageData, "base64"); fs.close(); this.setData({ localImgUrl: imgPath }) wx.previewImage({ urls: [imgPath] // 需要预览的图片http链接列表 }) } })
[Related learning recommendations:小programDevelopmentTutorial】
The above is the detailed content of How to view base64 images in the mini program. For more information, please follow other related articles on the PHP Chinese website!