Convert an Image to Base64 String in Python

In this tutorial, we will introduce the way to convert an image to base64 string using python base64 package.

1. Import library

import base64

2. Read an image data and convert it to base64 string

We can use base64.b64encode() function to convert.

with open("my_image.jpg", "rb") as img_file:
    my_string = base64.b64encode(img_file.read())
print(my_string)

The type of my_string is byte, we can convert it to string.

print(my_string.decode('utf-8'))