How to convert an image (png, jpg, etc) to base64 string using python ?

Published: September 02, 2022

Tags: Python; Base64; Protection Status

Example of how to convert a png image to base64 using python:

Install pybase64 module

with pip

pip install pybase64

with conda

conda install -c conda-forge pybase64

Convert a png image to base64

import base64

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


returns for example


Add an image encoded in base64 with markdown

The above string image can be used with markdown:

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


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