如何将 Base64 编码的图像保存到磁盘?
我的 Express 应用程序正在从浏览器接收 Base64 编码的 PNG(使用 toDataURL() 从画布生成)并将其写入文件。但该文件不是有效的图像文件,“文件”实用程序只是将其标识为“数据”。
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
});
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
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
我认为您转换的数据比您需要的要多一些。使用正确的编码创建缓冲区后,只需将缓冲区写入文件即可。
new Buffer(..., 'base64') 将输入字符串转换为 Buffer,它只是一个字节数组,通过将输入解释为 base64 编码的字符串。然后您可以将该字节数组写入文件。
更新
正如评论中提到的,
req.rawBody
不再是一个东西。如果您使用express
/connect
那么您应该使用bodyParser()
中间件并使用req.body
,如果您使用标准 Node 执行此操作,则需要聚合传入的data
事件Buffer
对象,并在end
中执行此图像数据解析打回来。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.
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.
Update
As mentioned in the comments,
req.rawBody
is no longer a thing. If you are usingexpress
/connect
then you should use thebodyParser()
middleware and usereq.body
, and if you are doing this using standard Node then you need to aggregate the incomingdata
eventBuffer
objects and do this image data parsing in theend
callback.这是我的完整解决方案,它将读取任何 base64 图像格式并将其以正确的格式保存在数据库中:
this is my full solution which would read any base64 image format and save it in the proper format in the database:
这对我来说简单而完美。
Scott Robinson 的精彩解释
来自图片到base64字符串
从base64字符串到图像
This did it for me simply and perfectly.
Excellent explanation by Scott Robinson
From image to base64 string
From base64 string to image
更新
我发现这个有趣的链接如何解决您的 PHP 问题。我认为您忘记将
space
替换为+
,如链接所示。我从 http://images-mediawiki- sites.thefullwiki.org/04/1/7/5/6204600836255205.png 作为示例,如下所示:
下一页我把它通过 http://www.greywyvern.com/code/php/binary2base64 返回了我:
将此字符串保存到我在代码中读取的
base64
。我得到了一个圆圈,但有趣的是文件大小已经改变:)...
结束
当你读回图像时我认为你需要设置标题
举个例子 imagepng:
我认为第二行
header('Content-Type: image/png');
,很重要,否则您的图像将不会显示在浏览器中,但是仅向浏览器显示一堆二进制数据。在 Express 中,您只需使用如下所示的内容即可。我将显示您的头像,其位于 http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG
当您
curl --head http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG
时,它是一个jpeg文件。我只请求标头,因为否则curl会在控制台显示一堆二进制内容(Google Chrome立即下载):app.js
UPDATE
I found this interesting link how to solve your problem in PHP. I think you forgot to replace
space
by+
as shown in the link.I took this circle from http://images-mediawiki-sites.thefullwiki.org/04/1/7/5/6204600836255205.png as sample which looks like:
Next I put it through http://www.greywyvern.com/code/php/binary2base64 which returned me:
saved this string to
base64
which I read from in my code.I get a circle back, but the funny thing is that the filesize has changed :)...
END
When you read back image I think you need to setup headers
Take for example imagepng from PHP page:
I think the second line
header('Content-Type: image/png');
, is important else your image will not be displayed in browser, but just a bunch of binary data is shown to browser.In Express you would simply just use something like below. I am going to display your gravatar which is located at http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG
and is a jpeg file when you
curl --head http://www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG
. I only request headers because else curl will display a bunch of binary stuff(Google Chrome immediately goes to download) to console:app.js
我还必须保存作为数据 URL 一部分的 Base64 编码图像,因此我最终制作了一个小型 npm 模块来执行此操作,以防我(或其他人)将来需要再次执行此操作。它称为 ba64。
简而言之,它获取带有 Base64 编码图像的数据 URL,并将图像保存到文件系统中。它可以同步或异步保存。它还具有两个辅助函数,一个用于获取图像的文件扩展名,另一个用于将 Base64 编码与
data:
方案前缀分开。这是一个示例:
安装它:
npm i ba64 -S
。仓库位于 GitHub 上:https://github.com/HarryStevens/ba64。PS 后来我发现 ba64 对于该模块来说可能是一个不好的名字,因为人们可能会认为它进行 Base64 编码和解码,但事实并非如此(有很多模块已经这样做了)。那好吧。
I also had to save Base64 encoded images that are part of data URLs, so I ended up making a small npm module to do it in case I (or someone else) needed to do it again in the future. It's called ba64.
Simply put, it takes a data URL with a Base64 encoded image and saves the image to your file system. It can save synchronously or asynchronously. It also has two helper functions, one to get the file extension of the image, and the other to separate the Base64 encoding from the
data:
scheme prefix.Here's an example:
Install it:
npm i ba64 -S
. Repo is on GitHub: https://github.com/HarryStevens/ba64.P.S. It occurred to me later that ba64 is probably a bad name for the module since people may assume it does Base64 encoding and decoding, which it doesn't (there are lots of modules that already do that). Oh well.
下面的函数保存文件,只需传递你的base64文件,它返回文件名将其保存在数据库中。
Below function to save files, just pass your base64 file, it return filename save it in DB.
您可以使用第三方库,例如 base64-img 或 base64-to-image。
You can use a third-party library like base64-img or base64-to-image.
从带有 base64 字符串的文件转换为 png 图像。
4 个可行的变体。
Converting from file with base64 string to png image.
4 variants which works.
将 base64 图像转换为文件并另存为随机 ID 或名称的简单方法。
Easy way to convert base64 image into file and save as some random id or name.
很简单
is very simple