Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you base-64 encode a PNG image for use in a data-uri in a CSS file?

I want to base-64 encode a PNG file, to include it in a data:url in my stylesheet. How can I do that?

I’m on a Mac, so something on the Unix command line would work great. A Python-based solution would also be grand.

like image 215
Paul D. Waite Avatar asked Jun 16 '11 17:06

Paul D. Waite


People also ask

Can a png be base64?

World's simplest online Portable Network Graphics image to base64 converter. Just import your PNG image in the editor on the left and you will instantly get a base64-encoded string on the right. Free, quick, and very powerful. Import a PNG – get base64.

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

How does base64 encoding work for images?

To display that base64 representation in a browser: Browser takes the image/png part and knows that the data following it will be the bytes of a png image. It then sees base64, and knows that the next blob will need to be base64 decoded, before it can then be decoded by its png decoder.


1 Answers

This should do it in Python:

import base64 encoded = base64.b64encode(open("filename.png", "rb").read()) 
like image 85
Jon Avatar answered Sep 23 '22 06:09

Jon