42

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

2
  • What kind of image is it? To send it to the client, you'll need to know what content-type the image is (JPEG, PNG, GIF, ICO)? Commented Feb 10, 2015 at 19:55
  • It's a PNG; I've edited my question to mention that. Commented Feb 10, 2015 at 19:56

3 Answers 3

111

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 = Buffer.from(data, 'base64');

   res.writeHead(200, {
     'Content-Type': 'image/png',
     'Content-Length': img.length
   });
   res.end(img); 
});
5
  • 3
    var img = new Buffer(data, 'base64');
    – lujcon
    Commented Feb 10, 2015 at 20:01
  • This is exactly what I needed! I replaced data.buffer with data as per @lujcon's comment and it works perfectly. Commented Feb 10, 2015 at 20:03
  • 9
    Thanks, works nicely, except that new Buffer(data, 'base64') is now deprecated... use Buffer.from(data, 'base64') instead
    – drmrbrewer
    Commented Dec 12, 2018 at 13:40
  • Thank You! "Content-Length" header was really important to me, otherwise, image was not just loading. Wasted 2 days in it but glad to have found the answer! Commented May 20, 2021 at 16:27
  • 1
    You need to remove the prefix (data:image\/png;base64) from the base64 String before Buffering it as image as @JayCrossler explains.
    – Gkiokan
    Commented Apr 24, 2022 at 16:19
27

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,/, '');
2
  • 1
    This should be the accepted answer, no third party required!
    – Luke Brown
    Commented Dec 23, 2020 at 18:49
  • 2
    You can also use var base64Data = data.split(',')[1] Commented Jun 5, 2022 at 16:38
13

Using "base64-img" component:

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

});

Not the answer you're looking for? Browse other questions tagged or ask your own question.