How to insert an image encoded in base64 in a jupyter notebook ?

Created September 02, 2022 | Viewed 517 | by Benjamin Edit


Example of how to insert an image encoded with base64 in a jupyter notebook ?

Encoding an image to base64 string represenation in python

First step is to convert a given image to a string encoded in base64, a solution is to use the python module pybase64.

Installation with pip

pip install pybase64

Installation with conda

conda install -c conda-forge pybase64

Convert a png image to base64

Now it is possible to convert an image called for example img.png to a string called here encoded_string

import base64

with open("img.png", "rb") as img_file:
    encoded_string = base64.b64encode(img_file.read())

print(encoded_string)

returns something like

b'iVBORw0KGgo...ozAAAAABJRU5ErkJggg=='

Insert base64 encoded image in a jupyter notebook

In a jupyter notebook, defined a cell as markdown text then enter

<img src="data:image/png;base64, encoded_string" >

For example:

<img src="data:image/png;base64,iVBORw0K...YKRozAAAAABJRU5ErkJggg==" />

References