NodeJS 编写 base64 图像文件 [英] NodeJS write base64 image-file

查看:31
本文介绍了NodeJS 编写 base64 图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 NodeJS-Server 收到一张 base64 编码的图片.

My NodeJS-Server receives a picture base64 encoded.

data:image/jpeg;base64,/9j/4QCcRXhpZgAASUkqAAgAAAA ... CiiigD//Z

接收到的数据应保存为jpg.因此我使用 Buffer 和 FileSystemWriter:

The received data should be saved as jpg. Therefore I use a Buffer and the FileSystemWriter:

var imageBuffer = new Buffer(data, 'base64'); //console = <Buffer 75 ab 5a 8a ...
fs.writeFile("test.jpg", imageBuffer, function(err) { //... });

fs.writeFile 不会抛出错误.保存了一个 jpeg 文件,但我无法打开它.图像查看器说:

the fs.writeFile doesn't throw an error. A jpeg-file is saved, but I can't open it. Image-Viewer says:

File is damaged or too big.

原文件6kb,新文件7kb.

The original file is 6kb large and the new file 7kb.

推荐答案

您必须从中剥离 url 元信息,即 data:image/jpeg 部分.(重申@CBroe 所说的)这是一个从输入字符串返回正确信息的小函数.

You have to strip the url meta information from it, the data:image/jpeg part. (Reiterating what @CBroe said) Here is a small function to return the correct information from the input string.

var data = 'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAA..kJggg==';

function decodeBase64Image(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;
}

var imageBuffer = decodeBase64Image(data);
console.log(imageBuffer);
// { type: 'image/jpeg',
//   data: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 00 b4 00 00 00 2b 08 06 00 00 00 d1 fd a2 a4 00 00 00 04 67 41 4d 41 00 00 af c8 37 05 8a e9 00 00 ...> }

然后您可以使用上述方法保存缓冲区.

Then you can save the buffer using your above method.

fs.writeFile('test.jpg', imageBuffer.data, function(err) { ... });

这篇关于NodeJS 编写 base64 图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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