Skip to content

API接口常用函数:base64转图片

Base64编码

Base64是一种用64个字符表示二进制数据的方法,常用于在文本协议(如JSON)中传输图片、文件等二进制数据。

示例代码

python
import base64
import io
from PIL import Image

def decode_image(base64_string, output_path=None):
    """将Base64字符串解码为图片
    
    Args:
        base64_string (str): Base64编码的图片字符串
        output_path (str, optional): 输出图片文件路径,如果不提供则只返回PIL Image对象
        
    Returns:
        PIL.Image: PIL图像对象
    """
    # 解码Base64字符串为二进制数据
    image_data = base64.b64decode(base64_string)
    
    # 创建BytesIO对象并生成PIL Image对象
    image = Image.open(io.BytesIO(image_data))
    
    # 如果指定了输出路径,保存图片到文件
    if output_path:
        image.save(output_path)
        print(f"图片已保存至: {output_path}")
    
    return image

# 使用示例1:将base64转换为PIL Image对象
base64_str = "iVBORw0KGgoAAAANSUhEUgAA..."  # 你的base64字符串
img = decode_image(base64_str)
img.show()  # 显示图片

# 使用示例2:将base64保存为文件
decode_image(base64_str, "output.png")

一个 Key 用全球大模型