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)?
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.
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.
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".
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.
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); });
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,/, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With