Rendering a Base64 PNG with Express

2019-01-18 04:16发布

问题:

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

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

Here, data is 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 img tag)?

回答1:

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

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

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


回答2:

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,/, '');