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.

  1. Open an image file.
  2. read the image data.
  3. encode it in base64 using the base64 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 base64
with open("my_image.jpg", "rb") as img_file:
    my_string = base64.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,

Leave a Reply

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