【问题标题】:Convert Base64 image to raw binary with Node.js使用 Node.js 将 Base64 图像转换为原始二进制文件
【发布时间】:2013-09-30 10:51:41
【问题描述】:

我找到了与我正在寻找的内容相近的帖子,但我未能成功实现我想要的内容。这是一般流程:

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

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

我想使用这样的 URL 提取图像:

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

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

【问题讨论】:

    标签: javascript node.js image base64 gridfs


    【解决方案1】:

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

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

    所以在你的实现中:

    server.get(version+'/images/:id', function(req, res) {
      gridfstore.read(req.params.id, function(err, data) {
        var img = Buffer.from(data.buffer, 'base64');
    
        res.writeHead(200, {
          'Content-Type': 'image/jpeg',
          'Content-Length': img.length
        });
        res.end(img); 
    
      });
    });
    

    【讨论】:

    • 感谢@hexacyanide,我尝试了您的建议,但它以无效图像的形式返回。缓冲区分配准确,长度准确,但图像不显示,所以我会做更多的挖掘,看看我是否可以提供更多信息。当我使用 Base64 数据 URI 并使用 在 HTML 页面中显示它时,它可以工作,所以至少我知道 Base64 是有效的。
    • 那么你想做什么?您是否只想在页面上显示图像?
    • 我试图简单地返回图像,就像您调用 http://[somehost]/someimage.jpg 一样。如果有帮助,我附上了截图。使用您建议的代码,浏览器只是时钟。另外,我在服务器上使用 Restify,但根据我的阅读,它支持 Node.js ServerResponse。 mcavage.me/node-restify/#Content-Negotiation
    • 就其价值而言,这就是我在 GridFS 中看到的数据。 "数据" : BinData(0,"ZGF0YTppbWFnZS9qcGVnO2Jhc2U2NCwvOWovNEFBUVNrWkpSZ0FCQWdB...
    • 啊!!当我将图像存储在 GridFS 中时,图像是 Base64 编码的,所以它是双重编码的。现在我正在存储一个单一编码的图像,一切正常。哇!感谢您的帮助
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-05-29
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多