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

相关推荐
weixin_lynhgworld2 小时前
淘宝扭蛋机小程序系统开发:重塑电商互动模式
大数据·小程序
996幸存者3 小时前
uni-app区域选择、支持静态、动态数据
微信小程序·uni-app
ᥬ 小月亮5 小时前
Uniapp编写微信小程序,绘制动态圆环进度条
微信小程序·小程序·uni-app
The_era_achievs_hero11 小时前
UniappDay03
vue.js·微信小程序·uni-app
说私域14 小时前
技术赋能与营销创新:开源链动2+1模式AI智能名片S2B2C商城小程序的流量转化路径研究
人工智能·小程序·开源
游戏开发爱好者81 天前
没有 Mac,如何上架 iOS App?多项目复用与流程标准化实战分享
android·ios·小程序·https·uni-app·iphone·webview
weixin_lynhgworld1 天前
代驾小程序系统开发:引领出行行业数字化转型
小程序
Python大数据分析1 天前
uniapp之微信小程序标题对其右上角按钮胶囊
微信小程序·小程序·uni-app
yzx9910131 天前
JS与Go:编程语言双星的碰撞与共生
java·数据结构·游戏·小程序·ffmpeg
说私域1 天前
基于开源链动2+1模式AI智能名片S2B2C商城小程序的私域流量池用户运营研究
人工智能·小程序·开源