使用Node.js将Base64图像转换为原始二进制文件 [英] Convert Base64 image to raw binary with Node.js

查看:356
本文介绍了使用Node.js将Base64图像转换为原始二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现的帖子与我要查找的内容很接近,但是我无法成功实现我想要的内容.这是一般流程:

I have found posts that are close to what I'm looking for, but I have not been able to successfully implement what I want. Here is the general flow:

  1. 提交包含其余场地数据的照片,作为base64数据
  2. 带状数据前缀(如果存在),所以我只有图像base64数据


var base64data = venue.image.replace(/^data:image\/png;base64,|^data:image\/jpeg;base64,|^data:image\/jpg;base64,|^data:image\/bmp;base64,/, '');


  1. 通过MongoDB将Base64数据存储在GridFS中(我正在使用 gridfstore )
  2. 然后,我想根据要求通过URL检索图像作为原始图像文件.


// generic images route
server.get(version+'/images/:id', function(req, res) {
  gridfstore.read( req.params.id, function(error,data) {
    res.writeHead(200, {
      'Content-Type': 'image/jpeg',
      'Content-Length': data.buffer.length
    });

    res.end(data.buffer);
  });
});

基本上,此方法返回GridFS中存储的Base64字节.我尝试了其他方法,但是它们不返回原始图像.

Basically, this method returns the Base64 bytes stored in GridFS. I have tried other methods but they don't return the raw image.

我想使用如下URL提取图片:

I'd like to pull up the image using URLs like this:

http://[localhost]/1/images/11dbcef0-257b-11e3-97d7-cbbea10abbcb

这是浏览器跟踪的屏幕截图:

Here is a screenshot of the browser trace:

推荐答案

您可以从MongoDB中获取字符串,创建新的缓冲区实例,并在执行此操作时指定编码.结果缓冲区将以二进制数据存储.

You can take the string from MongoDB, create a new buffer instance, and specify an encoding when doing so. The resultant buffer will be in binary data.

var b64str = /* whatever you fetched from the database */;
var buf = new Buffer(b64str, 'base64');

因此在您的实现中:

server.get(version+'/images/:id', function(req, res) {
  gridfstore.read(req.params.id, function(err, data) {
    var img = new Buffer(data.buffer, 'base64');

    res.writeHead(200, {
      'Content-Type': 'image/jpeg',
      'Content-Length': img.length
    });
    res.end(img); 

  });
});

这篇关于使用Node.js将Base64图像转换为原始二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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