✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Encode png bytes to base64


I`m trying to get png bytes from plotly and i use


After that Im trying to encode bytes like

  • “data:image/png;base64,” + str(base64.b64encode(img))

an this doesnt work. I`ve tried

  • urllib.parse.quote_from_bytes(img)

but this doesnt work too.

I`ve also try http://freeonlinetools24.com/base64-image to chek the base64 string, but it doesnot worked.

Can i use, somehow, py.image.get to make static image on my web-site ?

Hi @Luidgi

You almost had it with your first bullet. Rather than converting the base64 bytes object to a string using the str constructor, you need to decode it into a string using the .decode() method.

img = py.image.get(fig)
img_uri = "data:image/png;base64," + base64.b64encode(img).decode('utf8')

If you’re in the Jupyter Notebook you can check to make sure it worked by displaying img_uri as follows

from IPython.display import Image

Hope that helps!

1 Like

Thanks foe answer!

Also, I found the problem. Thhere are 3 excess characters in string of bytes.
This is wirking now :

  • plot_bytes_encode = str(base64.b64encode(img))
    plot_bytes_encode = plot_bytes_encode[0:-1]
    plot_bytes_encode_fin = plot_bytes_encode[2:]
    stringpic = “data:image/png;base64,” + plot_bytes_encode_fin