javascript 如何在 node.js 中将二进制缓冲区解码为图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32877273/
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-28 15:50:47  来源:igfitidea点击:

How to decode a binary buffer to an image in node.js?

javascriptnode.jsbufferfs

提问by Sarodh Uggalla

I'm receiving an image in a binary stream as shown below, however when I try to create a buffer with the following data the buffer appears to be empty. Is the problem that buffer doesn't understand this format?

我正在接收二进制流中的图像,如下所示,但是当我尝试使用以下数据创建缓冲区时,缓冲区似乎是空的。是不是buffer看不懂这种格式的问题?

V?q)?EB\u001599!F":"????\u000b??3??5%?L?\u0018??pO^::?~??m?<\u001e??L??k?%G?$b\u0003\u0011???=q?V=??A\u0018??O??U???m?B???\u00038?????0a?_??#\u001b????\f??(?3?\u0003???nGjr???Mt\?\u0014g????~?#?Q?? g?K??s??@C??\u001cS?`\u000bps?Gnzq?Rg?\fu???C\u0015?\u001d3?E.BI\u0007???

V?q)?EB\u001599!F":"????\u000b??3??5%?L?\u0018??pO^::?~??m?<\u001e??L? ?k?%G?$b\u0003\u0011???=q?V=??A\u0018??O??U???m?B???\u00038???0a?_ ??#\u001b????\f??(?3?\u0003???nGjr???Mt\?\u0014g????~?#?Q??g?K??s?? @C??\u001cS?​​`\u000bps?Gnzq?Rg?\fu???C\u0015?\u001d3?E.BI\u0007???

var buffer = new Buffer(req.body, 'binary')
    console.log("BUFFER:" + buffer)
fs.writeFile('test.jpg', buffer, function(err,written){
   if(err) console.log(err);
    else {
     console.log("Successfully written");
    }
});

采纳答案by Sarodh Uggalla

Problem was body-parser doesn't parse content-type: octet-stream and I was overriding the header to parse it as an url-encoded-form which the buffer didn't understand even though I was able to log the req.body. The middleware below allows for the parsing of content-type: octet-stream for body-parser.

问题是 body-parser 不解析 content-type: octet-stream 并且我正在覆盖标头以将其解析为 url-encoded-form,即使我能够记录 req.body,缓冲区也不理解该格式. 下面的中间件允许解析 content-type:body-parser 的 octet-stream。

app.use(function(req, res, next) {
   var contentType = req.headers['content-type'] || ''
   var mime = contentType.split(';')[0];
    // Only use this middleware for content-type: application/octet-stream
    if(mime != 'application/octet-stream') {
        return next();
    }
   var data = '';
   req.setEncoding('binary');
    req.on('data', function(chunk) { 
       data += chunk;
   });
   req.on('end', function() {
      req.rawBody = data;
      next();
  });
});

回答by berthni

I think you should set the encoding when you call fs.writeFile like this :

我认为您应该在像这样调用 fs.writeFile 时设置编码:

fs.writeFile('test.jpg', buffer, 'binary', function(err) {