Rendering a Base64 PNG with Express

44,753

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

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

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

Solution 3

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

});
Share:
44,753
Hydrothermal
Author by

Hydrothermal

I am a writer and full-stack web developer. Find me at http://hydrothermal.io.

Updated on August 31, 2021

Comments

  • Hydrothermal
    Hydrothermal over 2 years

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

  • lujcon
    lujcon over 9 years
    var img = new Buffer(data, 'base64');
  • Hydrothermal
    Hydrothermal over 9 years
    This is exactly what I needed! I replaced data.buffer with data as per @lujcon's comment and it works perfectly.
  • drmrbrewer
    drmrbrewer over 5 years
    Thanks, works nicely, except that new Buffer(data, 'base64') is now deprecated... use Buffer.from(data, 'base64') instead
  • Luke Brown
    Luke Brown over 3 years
    This should be the accepted answer, no third party required!
  • Adil Maqusood
    Adil Maqusood almost 3 years
    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!
  • Gkiokan
    Gkiokan about 2 years
    You need to remove the prefix (data:image\/png;base64) from the base64 String before Buffering it as image as @JayCrossler explains.
  • preciousbetine
    preciousbetine almost 2 years
    You can also use var base64Data = data.split(',')[1]