Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a Base64 PNG with Express

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

like image 296
Hydrothermal Avatar asked Feb 10 '15 19:02

Hydrothermal


People also ask

How do I encode a Base64 PNG?

Paste the URL or select a PNG image from your computer. If necessary, select the desired output format. Press the “Encode PNG to Base64” button. Download or copy the result from the “Base64” field.

Can a PNG be Base64?

To convert PNG to base64 data: Click on "Choose file" and upload the PNG image from your system. Click on the "Convert" button to convert the PNG image into base 64 data. You can "Download or Copy" the base 64 code for further use.

What format is data:image PNG Base64?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even). It's not "instead of providing an URL".

Why images are Base64 encoded?

Base64 encoding is a way to encode binary data in ASCII text. It's primarily used to store or transfer images, audio files, and other media online. It is also often used when there are limitations on the characters that can be used in a filename for various reasons.


2 Answers

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);  }); 
like image 127
Ben Diamant Avatar answered Sep 29 '22 13:09

Ben Diamant


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,/, ''); 
like image 36
JayCrossler Avatar answered Sep 29 '22 12:09

JayCrossler