1、base64图片转临时路径
/*** 将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
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,/, "")