SoFunction
Updated on 2025-03-01

How to read base64 image data in Python

Python reads base64 image data

In Python, you can usebase64The module decodes Base64 encoded strings and converts them back to the original data (such as pictures).

But usually, Base64-encoded image strings will be prefixed (such asdata:image/jpeg;base64,), you need to remove this prefix before decoding.

A simple example

Shows how to read and save an image from a Base64 encoded string:

import base64
import io
from PIL import Image

# Suppose there is a Base64 encoded image string, here we use a simplified examplebase64_str = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAAAAAAAAAD/4gIoSUNDX1BST0ZJTEUAAQEAAAIYAAAAAAIQAAABtbnRyUkdCIFhZJiouMjY7... (Other Base64 encoding contents are omitted here)"

# Remove the prefix ('data:image/jpeg;base64,')base64_data = base64_str.split(',')[1]

# Decode Base64 dataimage_bytes = base64.b64decode(base64_data)

# Convert byte data to BytesIO objectimage_io = (image_bytes)

# Read pictures using PIL libraryimage = (image_io)

# Save the picture to the file('')

Note: The Base64 string abovebase64_strJust an example, it needs to be replaced with the actual Base64 encoded picture string.

Also, the Base64 string may start with a different MIME type (e.g.data:image/png;base64,), the code needs to be adjusted accordingly to match the string.

Use scenarios

The following is an example of the application deployed by Baidu Aistudio:

# Get base64 image dataimport requests

def query(payload, token='Your own token token', appCode='Your appCode'):
    API_URL = f"https://{appCode}./image/generations"
    headers = {
        # Please go to /index/accessToken to view access token        "Authorization": f"token {token}",
        "Content-Type": "application/json"
    }
    response = (API_URL, headers=headers, json=payload)
    return ()

def access_image(prompt):
    output = query({
        "prompt": f"{prompt}"
    })
    return output['data'][0]["b64_image"]
# base64 data to picturesimport base64  
import io  
from PIL import Image  


def decode_b64_image(base64_data):
    # Decode Base64 data    image_bytes = base64.b64decode(base64_data)  

    # Convert byte data to BytesIO object    image_io = (image_bytes)  
    
    # Read pictures using PIL library    image = (image_io)  
    
    # Save the picture to the file    # ('')
    return image
# Call functionprompt = "Masterpiece, high quality, super fine, full detail, 8k"
base64_image = access_image(prompt)
decode_b64_image(base64_image)

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.