Convert Image to Base64 string in Python
In this tutorial, we will learn about how to convert an image to Base64 string in Python. We can represent an image with a string also known as Base64 string or Base64 code. So let’s learn how this conversion can be done in Python.
Convert an image to base64 string in Python
Here we will learn it step by step with an example.
At first, let’s talk about the steps we gonna follow in this tutorial.
- Open an image file.
- read the image data.
- encode it in base64 using the base64 module in Python.
- Print the string.
Here we will take an example image to show you how to do this.
Now we will convert this image to its base64 code using the below Python Program:
Python program: image to base64
import base64 with open("my_image.jpg", "rb") as img_file: my_string = base64.b64encode(img_file.read()) print(my_string)
Read more tutorial,
- Convert RGB to Binary Image in Python (Black and White)
- Read an image in Python and open it in a Window
As you can see here, your string has been printed. But in starting position of your base64 string there is a b’
Or you can say your base64 encoded string is in a pair of single quotation.
So how to remove that?
Remove b’ from the prefix of base64 code in Python
Just use the below line to print the base64 string without b’ ‘ in Python
Now it will print only the string you need without b’.
We just decoded the encoded string to utf-8 format.
The filename of my image is my_image.jpg
- At first, we opened our file in ‘rb’ mode.
- Then we read the image file and encoded it with the following line:
base64.b64encode(img_file.read()) – b64encode() is a method to encode the data into base64
- You must read the image file before you encode it.
Read more articles,