Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a base64 image string to a image file that can be served to browsers using node.js

The issue was to do with the HTTP ACCEPT header not being accepted by Restify, the image rendering code is fine.


I have an image encoded as a base64 string, and I want to serve this as an image using node.js. Currently I've got the following code (I'm using Restify) which renders the image in Chrome OK, but the image doesn't render in other browsers (tried IE9, Firefox 4, Android browser):

var decodedBuffer = new Buffer(dataString,"base64");            
    res.send({
          code: 200,
          headers: {'Content-Type': 'image/png', 'Content-Length': decodedBuffer.length},   
          noEnd: true                               
    });     

    res.write(decodedBuffer);                       
    res.end();  

Anyone able to shed some light on what I might be doing wrong??

Thanks

like image 515
Andy Britcliffe Avatar asked Nov 04 '22 20:11

Andy Britcliffe


1 Answers

Use data URI syntax, which means you have to prefix the response with the data protocol and the MIME type, plus specify base64 encoding:

res.write("data:image/png;base64,"+decodedBuffer);
like image 81
Paul Sweatte Avatar answered Nov 09 '22 02:11

Paul Sweatte