Pythondex
Python Conversion Programs

Convert Image To Base64 In Python

Last updated January 31, 2024 by Jarvis Silva

In this article we will see how to convert image to base64 file using python programming, to convert image to base64 we will use the preinstalled python library Base64 it allows us to decode base64 code,

Python Code To Convert Image to Base64


# Import base64 module
import base64

# Get image file
image_file = open("my_image.jpg", "rb")

# Convert to base64 string
bs64_str = base64.b64encode(image_file.read())
print(bs64_str)


Above is the python code for converting image to base64, in the code we encode the image file using the base64 encode method which gives us a base64 string.

You can run this code and see the result, to run this program you need to have python installed, if you don’t have, then read this: Install and setup python or you can use this online python compiler.

When you run the program you will see that it printed a base64 string of the image now if you want to see if it is the correct base64 you can convert the same string back to image for that you can follow this tutorial: Convert base64 to image in python.

Here are some more python programs you will find helpful:

I hope you found what you were looking for from this python tutorial, and if you want more python tutorials like this, do join our Telegram channel to get updated.

Thanks for reading, have a nice day 🙂