Convert an Image to Base64 String and vice versa in Python

avatar
Borislav Hadzhiev

Last updated: Apr 11, 2024
4 min

banner

# Table of Contents

  1. Convert an Image to a Base64-encoded String in Python
  2. Convert an Image to a Base64-encoded String using Pillow
  3. Converting a Bas64 string to an Image and saving it to the file system

# Convert an Image to a Base64-encoded String in Python

To convert an image to a base64 string in Python:

  1. Use the with open() statement to open the image file.
  2. Use the file.read() method to read the image's contents.
  3. Use the base64.b64encode() method to encode the bytes using Base64 and return a bytes-like object.
main.py
import base64 with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) print(base64_bytes) base64_string = base64_bytes.decode() print(base64_string)

convert image to base64 string in python

The code sample assumes that you have the following house.webp image in the same directory as your Python script.

house

You can right-click on the image and select "Save image as" to download it.

We first imported the base64 native Python module.

The module provides functions for encoding binary data to printable ASCII characters and decoding such encodings back to binary data.

The next step is to use the with open() statement to open the image file in rb (read binary) mode.

The with open() statement takes care of closing the file even if an error occurs.

main.py
import base64 with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) print(base64_bytes) base64_string = base64_bytes.decode() print(base64_string)

The base64.b64encode method encodes the supplied bytes-like object using Base64 and returns the encoded bytes.

If you want to convert the base64 encoded bytes to a string, use the bytes.decode() method.

main.py
base64_string = base64_bytes.decode() print(base64_string)

The bytes.decode() method converts the bytes object to a string and removes the b prefix.

You can also pass the encoding as an argument to the decode() method.

The default encoding is utf-8.

main.py
base64_string = base64_bytes.decode('utf-8') print(base64_string)

The first argument we passed to the open() function is the path to the image file.

If you are on Windows, prefix the path with r to mark it as a raw string.

main.py
image_path = r'C:\Users\Alice\Desktop\my-image.png'
Strings that are prefixed with r are called raw strings and treat backslashes as literal characters.

This is necessary because path components are separated by backslashes on Windows and have a special meaning in Python - they are used as escape characters (e.g. \n or \t).

You can also use another backslash to escape each backslash as an alternative.

main.py
image_path = 'C:\\Users\\Alice\\Desktop\\my-image.png'

An alternative approach is to use forward slashes instead of backslashes.

main.py
image_path = 'C:/Users/Alice/Desktop/my-image.png'

However, using a single backslash is not valid because the backslash character is used as an escape character and not as a separator of path components.

# Convert an Image to a Base64-encoded String using Pillow

You can also use the Pillow module to convert an image to a base64-encoded string.

First, install the module by running the following command in your terminal.

shell
pip install Pillow # or with pip3 pip3 install Pillow

Now import and use the module as follows.

main.py
from io import BytesIO import base64 from PIL import Image with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) print(base64_bytes) base64_string = base64_bytes.decode() print(base64_string) im = Image.open(BytesIO(base64.b64decode(base64_bytes))) im.save('house2.png', 'PNG')

We first open the house.webp image in rb (read binary) mode.

The base64.b64encode() method is used to encode the bytes-like image object using Base64.

If you need to convert the bytes to a string, use the bytes.decode() method.

If you need to open the image file using Pillow, use the Image.open() method.

The BytesIO class is a buffered I/O implementation using an in-memory bytes buffer.

main.py
im = Image.open(BytesIO(base64.b64decode(base64_bytes))) im.save('house2.png', 'PNG')

If you need to convert the file to a different content type, use the Image.save() method.

The first argument we passed to the method is the file name and the second is the format.

If no format is specified, the format is determined from the filename extension.

# Converting a Bas64 string to an Image and saving it to the file system

If you need to convert a bse64 string to an image and save it to the file system:

  1. Use the with open() statement to open the image file in wb (write bytes) mode.
  2. Use the file.write() method to write the decoded bytes to the file.
main.py
import base64 with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) print(base64_bytes) with open('house2.webp', 'wb') as file_handler: file_handler.write(base64.decodebytes(base64_bytes))

We first open the image file in rb (read bytes) mode.

The next step is to use the base64.b64encode() method to encode the bytes-like image object using Bas64, returning a bytes object.

We then open the new file in wb (write bytes) mode.

The base64.decodebytes() method decodes a bytes string of base-64 data into a bytes object.

The file.write() method writes the bytes to the file.

If you are starting with a string object, you can also use the Pillow library.

main.py
import io import base64 from PIL import Image with open('house.webp', 'rb') as image_file: base64_bytes = base64.b64encode(image_file.read()) base64_string = base64_bytes.decode() img = Image.open( io.BytesIO( base64.decodebytes(bytes(base64_string, 'utf-8')) ) ) img.save('house2.webp')

We convert the base64 string to an image and save it using the Image.save() method.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.