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

Paul D. Waite picture Paul D. Waite · Jun 16, 2011 · Viewed 45.1k times · Source

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.

Answer

Jon picture Jon · Jun 16, 2011

This should do it in Python:

import base64
encoded = base64.b64encode(open("filename.png", "rb").read())