Python Base64 to Image: Complete Guide

In Python, you can use the base64 library to convert base64 data to an image. Here is an example code for writing base64 data as an image:

import base64
import io
from PIL import Image

def write_base64_image(base64_data, file_path):
    # 解码base64数据
    image_data = base64.b64decode(base64_data)
    
    # 创建Image对象
    image = Image.open(io.BytesIO(image_data))
    
    # 保存图片
    image.save(file_path)

# 示例调用
base64_data = "base64数据"
file_path = "图片保存路径"
write_base64_image(base64_data, file_path)

In the sample code, the write_base64_image function takes two parameters: the base64 data and the file path to save the image. First, the base64 data is decoded into the original image data using the base64.b64decode function. Then, the image data is converted to a BytesIO object using io.BytesIO and passed to the Image.open function to create an Image object. Finally, the Image.save method is used to save the image to the specified file path.

bannerAds