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);
});
Author by
Hydrothermal
I am a writer and full-stack web developer. Find me at http://hydrothermal.io.
Updated on August 31, 2021Comments
-
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 animg
tag)? -
lujcon over 9 years
var img = new Buffer(data, 'base64');
-
Hydrothermal over 9 yearsThis is exactly what I needed! I replaced
data.buffer
withdata
as per @lujcon's comment and it works perfectly. -
drmrbrewer over 5 yearsThanks, works nicely, except that
new Buffer(data, 'base64')
is now deprecated... useBuffer.from(data, 'base64')
instead -
Luke Brown over 3 yearsThis should be the accepted answer, no third party required!
-
Adil Maqusood almost 3 yearsThank 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 about 2 yearsYou need to remove the prefix (
data:image\/png;base64
) from the base64 String before Buffering it as image as @JayCrossler explains. -
preciousbetine almost 2 yearsYou can also use
var base64Data = data.split(',')[1]