Javascript 使用 Express 渲染 Base64 PNG

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

Rendering a Base64 PNG with Express

javascriptnode.jsimageexpressbase64

提问by Hydrothermal

My Node.js server has something that looks like the following:

我的 Node.js 服务器具有如下所示的内容:

app.get("/api/id/:w", function(req, res) {
    var data = getIcon(req.params.w);
});

Here, datais a string containing a Base64 representation of a PNG image. Is there any way I can send this to a client accessing the route encoded and displayed as an image (e.g. so the URL can be used in an imgtag)?

这里,data是一个包含 PNG 图像的 Base64 表示的字符串。有什么方法可以将其发送给访问编码并显示为图像的路由的客户端(例如,URL 可以在img标签中使用)?

回答by Ben Diamant

Yes you can encode your base64 string and return it to the client as an image:

是的,您可以对 base64 字符串进行编码并将其作为图像返回给客户端:

server.get("/api/id/:w", function(req, res) {
    var data = getIcon(req.params.w);
    var img = Buffer.from(data, 'base64');

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

回答by JayCrossler

I had to do a bit of manipulation first to get mine in the right format, but this worked great:

我必须先做一些操作才能使我的格式正确,但这很有效:

  var base64Data = data.replace(/^data:image\/png;base64,/, '');

回答by gtrujillos

Using "base64-img" component:

使用“base64-img”组件:

app.get('/image1', function(req, res) {

  var image1 = 'image1.jpg';

  var base64Img = require('base64-img');
  var imageData1 = base64Img.base64Sync(image1);
  var base64Data = imageData1.replace(/^data:image\/(png|jpeg|jpg);base64,/, '');
  var img = Buffer.from(base64Data, 'base64');

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

});