如何将 base64 编码的图像保存到磁盘? [英] How can I save a base64-encoded image to disk?
问题描述
My Express 应用程序正在从浏览器接收 base64 编码的 PNG(从画布使用 toDataURL() 生成)并将其写入文件.但该文件不是有效的图像文件,文件"实用程序只是将其标识为数据".
My Express app is receiving a base64-encoded PNG from the browser (generated from canvas with toDataURL() ) and writing it to a file. But the file isn't a valid image file, and the "file" utility simply identifies it as "data".
var body = req.rawBody,
base64Data = body.replace(/^data:image/png;base64,/,""),
binaryData = new Buffer(base64Data, 'base64').toString('binary');
require("fs").writeFile("out.png", binaryData, "binary", function(err) {
console.log(err); // writes out file without error, but it's not a valid image
});
推荐答案
我认为您转换的数据比您需要的要多一些.使用正确的编码创建缓冲区后,您只需要将缓冲区写入文件即可.
I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.
var base64Data = req.rawBody.replace(/^data:image/png;base64,/, "");
require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
console.log(err);
});
new Buffer(..., 'base64') 通过将输入解释为 base64 编码字符串,将输入字符串转换为 Buffer,它只是一个字节数组.然后你可以将该字节数组写入文件.
new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.
正如评论中提到的,req.rawBody
不再是一个东西.如果你使用 express
/connect
那么你应该使用 bodyParser()
中间件并使用 req.body
,如果您使用标准节点执行此操作,则需要聚合传入的 data
事件 Buffer
对象并在 end
中执行此图像数据解析回调.
As mentioned in the comments, req.rawBody
is no longer a thing. If you are using express
/connect
then you should use the bodyParser()
middleware and use req.body
, and if you are doing this using standard Node then you need to aggregate the incoming data
event Buffer
objects and do this image data parsing in the end
callback.
这篇关于如何将 base64 编码的图像保存到磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!