How to Convert Base64 to Image Using Python

Dec 16, 2023

2 mins read

Published in

Base64 encoding is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It is commonly used for encoding data in URLs, data URIs, and other situations where binary data needs to be transmitted or stored as text.

Remember to install the necessary packages before running the code: pip install pillow

Converting Base64 to Image

To convert a Base64 string to an image in Python, we can use the base64 module to decode the string and the PIL (Pillow) library to work with images. Here’s a step-by-step guide:

  1. Import Required Libraries:

    1
    2
    3
    
    import base64
    from PIL import Image
    from io import BytesIO
    
  2. Decode Base64 String:

    1
    2
    3
    4
    5
    6
    7
    8
    
    def base64_to_image(base64_string):
        # Remove the data URI prefix if present
        if "data:image" in base64_string:
            base64_string = base64_string.split(",")[1]
    
        # Decode the Base64 string into bytes
        image_bytes = base64.b64decode(base64_string)
        return image_bytes
    
  3. Create Image from Bytes:

    1
    2
    3
    4
    5
    6
    7
    
    def create_image_from_bytes(image_bytes):
        # Create a BytesIO object to handle the image data
        image_stream = BytesIO(image_bytes)
    
        # Open the image using Pillow (PIL)
        image = Image.open(image_stream)
        return image
    
  4. Usage:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    def main():
        # Replace this with your Base64 string
        base64_string = "your_base64_string_here"
    
        # Convert Base64 to image bytes
        image_bytes = base64_to_image(base64_string)
    
        # Create an image from bytes
        img = create_image_from_bytes(image_bytes)
    
        # Display or save the image as needed
        img.show()
        # img.save("output_image.jpg")
    

Converting a Base64 string to an image in Python is a straightforward process using the base64 module for decoding and the PIL library for image manipulation. Whether you’re working with image uploads, data extraction, or any other scenario involving Base64-encoded images, this tutorial should provide a solid foundation.

Sharing is caring!