javascript 使用 Node.js 将 Base64 图像转换为原始二进制文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18994881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:00:11  来源:igfitidea点击:

Convert Base64 image to raw binary with Node.js

javascriptnode.jsimagebase64gridfs

提问by remotevision

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. Submit photo with rest of venue data, as base64 data
  2. Strip data prefix if it exists, so I have just the image base64 data
  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. Store Base64 data in GridFS via MongoDB (I'm using gridfstore)
  2. Then, I'd like to retrieve the image upon request as a raw image file via a URL.
  1. 通过 MongoDB 在 GridFS 中存储 Base64 数据(我正在使用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);
  });
});

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

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

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

我想使用这样的 URL 拉出图像:

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

Here is a screenshot of the browser trace: browser trace

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

回答by hexacyanide

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.

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

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

So in your implementation:

所以在你的实现中:

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); 

  });
});

回答by John Williams

Make sure your string is correct. This worked for me..

确保你的字符串是正确的。这对我有用..

var buf = new Buffer(b64stringhere, 'base64');
var express = require('express'), app = express();
app.get('/img', function(r, s){
    s.end(buf);
})
app.listen(80);