Explore

Python Programs

Convert Base64 To Image In Python

Convert Base64 To Image In Python

Looking for a tutorial on how to convert base64 to image in python then you are at the right place, Today in this article I will show you how to convert base64 to image file using python programming.

To convert base64 to image we will use the python library Base64 it allows us to decode base64 code, It comes preinstalled with python so you don’t have to install it.

Python Code To Convert Base64 To Image


# Import base64 module
import base64
 
# Get the base64 file data 
with open('base64.txt', 'rb') as bs64_file:
    bs64_data = bs64_file.read()

# Decode base64
decoded_img_data = base64.b64decode((bs64_data))

# Create image file from base64
with open('output.jpeg', 'wb') as img_file:
    img_file.write(decoded_img_data)

Above is the python code to convert base64 to image. 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.

Before running this program you need to enter the base64 file path so that it can read the base64 code.

Follow this steps to run this program:

  • First, create a new folder for this program.
  • Open it in a code editor of your choice.
  • Create a python file with .py extension.
  • Copy the above code and paste it in your file.
  • Open a terminal or CMD at folder location
  • And type this command python filename.py (Name of your py file).

After running the program you will see that it create a image file in your folder and if you open it you will see the image. Want to know how to convert image to base64 then read this article: Convert image to base64 in python.

Summary

This was the tutorial on converting base64 to image in python. I hope you found this tutorial helpful and useful. Do share this tutorial with your friends who might need this or find it helpful.

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 🙂