Search code examples
pythoncssimagebase64data-uri

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.


Solution

  • This should do it in Python:

    import base64
    
    binary_fc       = open(filepath, 'rb').read()  # fc aka file_content
    base64_utf8_str = base64.b64encode(binary_fc).decode('utf-8')
    
    ext     = filepath.split('.')[-1]
    dataurl = f'data:image/{ext};base64,{base64_utf8_str}'
    

    Thanks to @cnst comment, we need the prefix data:image/{ext};base64,

    Thanks to @ramazanpolat answer, we need the decode('utf-8')