微信小程序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 天前
【开题答辩全过程】以 基于微信小程序校园综合服务平台的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
Thetimezipsby1 天前
基于Taro4打造的一款最新版微信小程序、H5的多端开发简单模板
前端·javascript·微信小程序·typescript·html5·taro
從南走到北1 天前
JAVA同城打车小程序APP打车顺风车滴滴车跑腿源码微信小程序打车源码
java·开发语言·微信·微信小程序·小程序
猫七先生1 天前
微信小程序一键登录可行性方案
前端·微信小程序
canglingyue1 天前
微信小程序截屏与录屏功能详解
微信小程序·小程序
微三云-轩1 天前
区块链系统:解决549 亿元积分商城是否违法的问题
大数据·小程序·重构·区块链·生活
D155540880581 天前
电竞护航小程序成品搭建三角洲行动护航小程序开发俱乐部点单小程序成品游戏派单小程序定制
游戏·小程序
说私域2 天前
兴趣电商内容数据洞察未来市场走向研究——基于开源AI智能名片链动2+1模式S2B2C商城小程序的实践
人工智能·小程序
吴传逞2 天前
记一次uniapp微信小程序开发scss变量失效的问题
微信小程序·uni-app·scss
wmsj05782 天前
小程序图片批量保存太麻烦?用这款工具一键搞定,附工具教程!
小程序