将 Base64 缓冲区作为图像保存到磁盘
Saving Base64 Buffer as an image to the Disk
在 Node.js
应用程序中,我通过 Socket.io
将图像发送到服务器。在服务器中,我是这样得到它的,我想将它保存在磁盘上。它保存了,但我无法打开该图像,图像查看器说它已损坏!文件大小正确,但我无法打开它。代码中有什么我遗漏的吗?
socket.on('newImage', function (data) {
var img = data.image;
var coded_img = new Buffer(img, 'base64');
fs.writeFile("out.png", coded_img,'base64', function(err) {
if (err) throw err;
console.log('File saved.')
});
});
我解决了,有了这个功能,我恢复了主图数据:
decodeBase64Image = function(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
response = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
};
在 Node.js
应用程序中,我通过 Socket.io
将图像发送到服务器。在服务器中,我是这样得到它的,我想将它保存在磁盘上。它保存了,但我无法打开该图像,图像查看器说它已损坏!文件大小正确,但我无法打开它。代码中有什么我遗漏的吗?
socket.on('newImage', function (data) {
var img = data.image;
var coded_img = new Buffer(img, 'base64');
fs.writeFile("out.png", coded_img,'base64', function(err) {
if (err) throw err;
console.log('File saved.')
});
});
我解决了,有了这个功能,我恢复了主图数据:
decodeBase64Image = function(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
response = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
};