How to convert MIME png back to a regular image

Hello, all.

I am working on a project that heavily depends on Jupyter notebooks. Specifically, I have hit a bump when parsing notebooks to extract the cell outputs.

I found out that Matplotlib plots or any image generated using code gets saved into the underlying JSON as “image/png”. For example:

"image/png": "iVBORw0KGgoAAAANSUhEUgAAArwAAAEkCAYA......"

(the full image string can be found from this gist)
From that string I want to recreate the image outside jupyter notebooks. Any ideas?

I have tried converting it to bytes string in Python with bytes("image_string", "utf-8") but can’t make it work. Please help!

Based on this stackoverflow post, this worked:

<line_from_your_gist_assigning_to_string>
import base64
with open("imageToSave.png", "wb") as fh:
    fh.write(base64.decodebytes(str.encode(string)))

Replace the <line_from_your_gist_assigning_to_string> with the raw content of your gist.

Used the route of my_str_as_bytes from this stackoverflow post to convert your string text to bytes.
However, I found that replacing the str.encode(string) part of my suggested code with string.encode(), and according to Antti Haapala’s answer that may perhaps be better.

2 Likes

Thank you very much. This is massively helpful!

For future reference The Notebook file format — nbformat 5.1 documentation indicates that image/png is encoded as base64.

2 Likes