微信小程序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,/, "")

相关推荐
用户4324281061142 天前
微信小程序从0到1接入微信支付的完整攻略
微信小程序
spmcor3 天前
微信小程序 setStorageSync 踩坑实录:别让"顺手一存"变成"隐形炸弹"
微信小程序
用户4324281061144 天前
小程序埋点设计规范:如何设计可扩展的数据采集体系
微信小程序
m0_526119404 天前
iconfont我修改好颜色,但是在小程序项目是黑色的
小程序
2601_956743685 天前
2026 上海小程序开发甄选:源码、云函数、跨端兼容技术评判
小程序·开发经验·上海
IT_张三5 天前
CSDN-项目分享-暑期备考小程序
小程序
IsJunJianXin5 天前
pdd小程序 cdp 保存响应体
linux·服务器·小程序·pdd小程序·拼多多响应体解密·小程序cdp·拼多多rpc取响应体
Geek_Vison5 天前
APP瘦身实战:从80MB+砍到15MB——基于小程序容器技术剥离APP非核心业务的实践分享
小程序·uni-app·mpaas
weikecms5 天前
聚合返利CPS小程序快速搭建教程
人工智能·微信·小程序
Haibakeji6 天前
长沙餐饮门店点餐配送小程序定制开发
大数据·小程序