node图片转base64与base64转图片
# base64转图片
const fs = require('fs');
const path = 'temp.png';
//去掉图片base64码前面部分data:image/png;base64
const base64 = data.replace(/^data:image\/\w+;base64,/, "");
//把base64码转成buffer对象,新版本中使用`new Buffer.from(base64, 'base64')`
const dataBuffer = new Buffer(base64, 'base64');
fs.writeFile(path, dataBuffer, function(err){//用fs写入文件
if(err){
console.log(err);
}else{
console.log('写入成功!');
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 图片转base64
const fs = require("fs");
const util = require("util");
const imageData = await util.promisify(fs.readFileSync(fileUrl)); // 例:xxx/xx/xx.png
const imageBase64 = imageData.toString("base64");
const imagePrefix = "data:image/png;base64,";
console.log(imagePrefix + imageBase64);
1
2
3
4
5
6
2
3
4
5
6
上次更新: 2023/09/22, 16:54:32