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
Links | Site |
---|---|
Encoding and Decoding Base64 Strings in Python | stackabuse.com |
Convert Image to Base64 string in Python | codespeedy |
Convert Image to Base64 string in Python | codespeedy |
Matplotlib graphic image to base64 | stackoverflow |
Converting matplotlib png to base64 for viewing in html template | stackoverflow |
conda-forge | anaconda.org |
4 ways to insert images in Jupyter Notebook | mljar.com |
Is it possible to directly embed an image into a Markdown document? | superuser.com |