微信小程序base64图片与临时路径互相转换

1、base64图片转临时路径

javascript 复制代码
/**
   * 将base64图片转临时路径
   * @param {*} dataurl
   * @param {*} filename
   * @returns
   */
  base64ImgToFile(dataurl, filename = "file") {
    const base64 = dataurl; // base64码
    const time = new Date().getTime();
    const imgPath = wx.env.USER_DATA_PATH + "/poster" + time + "share" + ".png";
    //如果图片字符串不含要清空的前缀,可以不执行下行代码.**假如不清除,真机会报错**
    const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
    const fs = wx.getFileSystemManager();
    fs.writeFileSync(imgPath, imageData, "base64");
    fs.close();
    return imgPath;
  },

2、临时路径转base64

javascript 复制代码
  fileToBase64Img(tempFilePath) {
    wx.getFileSystemManager().readFile({
      // 读取本地文件内容
      filePath: tempFilePath,
      encoding: "base64", //编码格式
      success(res) {
        let base64 = "data:image/png;base64," + res.data;
        return base64;
      },
    });
  },

注意:小程序保存base64出错,Unhandled promise rejection Error: writeFileSync:fail base64 encode error

解决方式,清除data:image/png;base64 前缀

如:base64.replace(/^data:image\/\w+;base64,/, "")

相关推荐
大米饭消灭者1 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround2 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround2 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
吴声子夜歌2 天前
小程序——布局示例
小程序
码云数智-大飞2 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54592 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序
Slow菜鸟2 天前
微信小程序开发(二)目录结构完全指南
微信小程序·小程序
攀登的牵牛花3 天前
给女朋友写了个轻断食小程序:去老丈人家也是先动筷了
前端·微信小程序
前端小雪的博客.3 天前
【保姆级教程】uniAI 插件高效开发 uni-app 微信小程序(附实战案例)
微信小程序·uni-app·ai编程·uniai
小小王app小程序开发3 天前
海外盲盒小程序抽赏玩法分析(附跨境技术落地要点)
小程序