我的Express应用程序从浏览器接收base64编码的PNG (使用toDataURL()从canvas生成),并将其写入文件。但是该文件不是有效的图像文件," file“实用程序只是将其标识为"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
});
发布于 2011-08-04 05:17:26
我认为你转换的数据比你需要的要多一点。一旦使用正确的编码创建了缓冲区,您只需要将缓冲区写入到文件中。
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编码的字符串,将输入字符串转换为缓冲区,缓冲区只是一个字节数组。然后,您只需将该字节数组写入文件。
更新
正如评论中提到的,req.rawBody
不再是一个东西。如果使用express
/connect
,则应使用bodyParser()
中间件并使用req.body
,如果使用标准节点执行此操作,则需要聚合传入的data
事件Buffer
对象,并在end
回调中执行此图像数据解析。
发布于 2014-10-16 14:26:18
这是我的完整解决方案,它可以读取任何base64图像格式,并将其以适当的格式保存在数据库中:
// Save base64 image to disk
try
{
// Decoding base-64 image
// Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file
function decodeBase64Image(dataString)
{
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response = {};
if (matches.length !== 3)
{
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
}
// Regular expression for image type:
// This regular image extracts the "jpeg" from "image/jpeg"
var imageTypeRegularExpression = /\/(.*?)$/;
// Generate random string
var crypto = require('crypto');
var seed = crypto.randomBytes(20);
var uniqueSHA1String = crypto
.createHash('sha1')
.update(seed)
.digest('hex');
var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...';
var imageBuffer = decodeBase64Image(base64Data);
var userUploadedFeedMessagesLocation = '../img/upload/feed/';
var uniqueRandomImageName = 'image-' + uniqueSHA1String;
// This variable is actually an array which has 5 values,
// The [1] value is the real image extension
var imageTypeDetected = imageBuffer
.type
.match(imageTypeRegularExpression);
var userUploadedImagePath = userUploadedFeedMessagesLocation +
uniqueRandomImageName +
'.' +
imageTypeDetected[1];
// Save decoded binary image to disk
try
{
require('fs').writeFile(userUploadedImagePath, imageBuffer.data,
function()
{
console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
});
}
catch(error)
{
console.log('ERROR:', error);
}
}
catch(error)
{
console.log('ERROR:', error);
}
发布于 2017-10-15 20:26:01
我还必须保存Base64编码的图像,这些图像是数据URL的一部分,所以我最终做了一个小的npm模块来做这件事,以防我(或其他人)将来需要再次做这件事。它被称为ba64。
简单地说,它获取一个包含Base64编码图像的data URL,并将图像保存到您的文件系统。它可以同步或异步保存。它还有两个助手函数,一个用于获取图像的文件扩展名,另一个用于从data:
方案前缀中分离Base64编码。
下面是一个例子:
var ba64 = require("ba64"),
data_url = "data:image/jpeg;base64,[Base64 encoded image goes here]";
// Save the image synchronously.
ba64.writeImageSync("myimage", data_url); // Saves myimage.jpeg.
// Or save the image asynchronously.
ba64.writeImage("myimage", data_url, function(err){
if (err) throw err;
console.log("Image saved successfully");
// do stuff
});
安装它:npm i ba64 -S
。回购在GitHub:https://github.com/HarryStevens/ba64上。
附注:后来我想到,ba64可能不是一个好名字,因为人们可能会认为它会进行Base64编码和解码,但事实并非如此(有很多模块已经做到了这一点)。哦,好吧。
https://stackoverflow.com/questions/6926016
复制相似问题