如何将base64编码的图像保存到磁盘? [英] How can I save a base64-encoded image to disk?

查看:106
本文介绍了如何将base64编码的图像保存到磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Express应用程序正在从浏览器(使用toDataURL()从canvas生成)中接收base64编码的PNG,并将其写入文件.但是该文件不是有效的图片文件,文件"实用程序只是将其标识为数据".

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 ,如果使用标准Node进行此操作,则需要汇总传入的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆