How to view base64 images in the mini program

青灯夜游
Release: 2021-12-13 10:11:32
forward
5983 people have browsed it

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!

How to view base64 images in the mini program

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:

  • windows development tools black screen
  • Some Android models cannot display
  • Console error, etc.

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

How to view base64 images in the mini program

Solution

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链接列表
    })
  }
})
Copy after login

[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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template