javascript - 如何在Nodejs中将base64解码为图像?
问题描述
我正在通过套接字发送编码为 base64 的图像,但解码不起作用。必须包含新图像的文件被写为 base64 而不是 jpg 文件。
编码套接字:
function encode_base64(filename) {
fs.readFile(path.join(__dirname, filename), function (error, data) {
if (error) {
throw error;
} else {
console.log(data);
var dataBase64 = data.toString('base64');
console.log(dataBase64);
client.write(dataBase64);
}
});
}
rl.on('line', (data) => {
encode_base64('../image.jpg')
})
解码插座:
function base64_decode(base64str, file) {
var bitmap = new Buffer(base64str, 'base64');
fs.writeFileSync(file, bitmap);
console.log('****** File created from base64 encoded string ******');
}
client.on('data', (data) => {
base64_decode(data,'copy.jpg')
});
// the first few characters in the new file
//k1NRWuGwBGJpmHDTI9VcgOcRgIT0ftMsldCjFJ43whvppjV48NGq3eeOIeeur
解决方案
更改编码功能,如下所示。另外,请记住 new Buffer() 已被弃用,因此请使用 Buffer.from() 方法。
function encode_base64(filename) {
fs.readFile(path.join(__dirname, filename), function (error, data) {
if (error) {
throw error;
} else {
//console.log(data);
var dataBase64 = Buffer.from(data).toString('base64');
console.log(dataBase64);
client.write(dataBase64);
}
});
}
并解码如下:
function base64_decode(base64Image, file) {
fs.writeFileSync(file,base64Image);
console.log('******** File created from base64 encoded string ********');
}
client.on('data', (data) => {
base64_decode(data,'copy.jpg')
});
推荐阅读
- python - 使用 python asyncio 同时从两个端口接收数据包的 UDP 服务器
- hibernate - 如何完全加载实体?
- html - 如何将 flex 中的文本与徽标对齐
- html - 如何按比例调整子图像的大小?
- r - R ggplot2同一轴的多个刻度
- javascript - 单击时将数据加载到网格中返回未捕获(承诺中)TypeError:无法读取未定义的属性(读取'dataState')
- qt - Qt Creator5.0.2 运行错误dyld: Symbol not found: __cg_DGifCloseFile
- ios - 将嵌套的 div 类添加到 blockerList.json
- python - 在弹出窗口中选择元素不会复制我手动单击它时发生的情况
- ios - Interface should be changed before time-consuming task starts in Swift