How do you base-64 encode a PNG image for use in a data-uri in a CSS file?
In python3, base64.b64encode
returns a bytes
instance, so it's necessary to call decode
to get a str
, if you are working with unicode text.
# Image data from [Wikipedia][1]>>>image_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x05\x00\x00\x00\x05\x08\x06\x00\x00\x00\x8do&\xe5\x00\x00\x00\x1cIDAT\x08\xd7c\xf8\xff\xff?\xc3\x7f\x06 \x05\xc3 \x12\x84\xd01\xf1\x82X\xcd\x04\x00\x0e\xf55\xcb\xd1\x8e\x0e\x1f\x00\x00\x00\x00IEND\xaeB`\x82'# String representation of bytes object includes leading "b" and quotes, # making the uri invalid.>>> encoded = base64.b64encode(image_data) # Creates a bytes object>>> 'data:image/png;base64,{}'.format(encoded)"data:image/png;base64,b'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='"# Calling .decode() gets us the right representation>>> encoded = base64.b64encode(image_data).decode('ascii')>>> 'data:image/png;base64,{}'.format(encoded)'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
If you are working with bytes
directly, you can use the output of base64.b64encode
without further decoding.
>>> encoded = base64.b64encode(image_data)>>> b'data:image/png;base64,' + encodedb'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='