Convert WeChat applet uni-app pictures to base64

Convert uni-app pictures to base64 and vice versa


Select an image from your mobile phone to convert to base64:

getToBase64(){
    
    
  wx.chooseImage({
    
    
    count:'1',   // 最多可以选择的图片张数
    sizeType: ['original', 'compressed'], // ['原图','压缩图']
    sourceType: ['album', 'camera'],  // ['从相册选图','使用相机']
    success: res => {
    
    
    wx.getFileSystemManager().readFile({
    
    
        filePath: res.tempFilePaths[0], //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => {
    
     //成功的回调
          console.log('data:image/png;base64,' + res.data)
        }
      })
    }
  })
},

Convert online images to base64 or hexadecimal:

getToBase64Two(){
    
    
  var httpsimg = 'https://baidu.com/a.jpg'   // 网络图片地址
  wx.downloadFile({
    
         // 需要先下载 
    url: httpsimg,
    success(res) {
    
    
      console.log(res,'res')
      wx.getFileSystemManager().readFile({
    
    
          filePath: res.tempFilePath, //选择图片返回的相对路径
          encoding: 'base64', //编码格式:base64 | hex(16进制)
          success: res => {
    
     //成功的回调
            let userImageBase64 = 'data:image/jpg;base64,' + res.data;
            console.log(userImageBase64); // 打印base64格式图片
          }
      })
    }
  })
},

Convert base64 image to local image:

getToLocal(){
    
    
 var base64data = "";   // base64
  const fsm = wx.getFileSystemManager();
  const FILE_BASE_NAME = 'tmp_base64src'; //自定义文件名
  const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
  if (!format) {
    
    
    return (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(r) {
    
    
      console.log(r,'r')
      console.log(filePath,'filePath')
    },
    fail() {
    
    
      return (new Error('ERROR_BASE64SRC_WRITE'));
    },
  });
},

The above code is for reference only, and the specific implementation details and styles can be adjusted according to needs.


How to obtain source code:

Friends who need the complete source code, I hope you can like + favorite + comment, and then send me a private message~

Member learning group: [One-to-one Q&A]

If there is anything you don’t understand in the tutorial, you can add a learning member assistant for consultation (WeChat: mifankeji77)

Guess you like

Origin blog.csdn.net/weixin_42317757/article/details/130967030
Recommended