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.

Update: Previously this package was known as  base64 and now it’s changed to pybase64

Convert an image to base64 string in Python

At first you need to install the mentioned package. You can install it by using the following command:

pip install pybase64

The link is: https://pypi.org/project/pybase64/

Here we will learn it step by step with an example.

At first, let’s talk about the steps we are going to follow in this tutorial.

  1. Open an image file.
  2. read the image data.
  3. encode it in base64 using the pybase64 module in Python.
  4. Print the string.

Here we will take an example image to show you how to do this.

 

convert image to base64 in Python

filename: my_image.jpg

Now we will convert this image to its base64 code using the below Python Program:

Python program: image to base64

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

Output:

b'your_base64_string_will_be_printed_here'

Read more tutorial,

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

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

Now it will print only the string you need without b’.

We just decoded the encoded string to utf-8 format.

Explanation:

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,

One response to “Convert Image to Base64 string in Python”

  1. hakan says:

    bro how i can imshow or display on the web template with flask ??

Leave a Reply

Your email address will not be published. Required fields are marked *