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

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

Leave a Comment