Skip to content

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

Base64编码

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

如果图片文件是 .file 或其他扩展名,也需要转成base64再给大模型处理。

常用工具函数

图片转Base64

python
def encode_image(image_path):
    """将本地图片编码为Base64字符串
    
    Args:
        image_path (str): 本地图片文件路径
        
    Returns:
        str: Base64编码后的字符串
    """
    with open(image_path, "rb") as image_file:
        # 读取图片二进制数据并编码为Base64
        return base64.b64encode(image_file.read()).decode("utf-8")

# 使用示例
image_data = encode_image("example.png")  # 替换为你的图片路径

Base64转图片

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")

在线图片转Base64

python
import requests
import base64

def encode_image_from_url(image_url):
    """从网络URL获取图片并转换为Base64
    
    Args:
        image_url (str): 图片的网络URL
        
    Returns:
        str: Base64编码后的字符串
    """
    try:
        # 下载图片数据
        response = requests.get(image_url)
        response.raise_for_status()  # 检查HTTP错误
        
        # 编码为Base64
        return base64.b64encode(response.content).decode("utf-8")
    
    except requests.RequestException as e:
        print(f"下载图片失败: {e}")
        return None

# 使用示例
image_url = "https://example.com/image.jpg"
base64_data = encode_image_from_url(image_url)

注意事项

  1. 文件格式支持:支持常见的图片格式如PNG、JPG、JPEG、GIF、BMP等
  2. 大小限制:Base64编码会增加约33%的数据大小,注意API接口的大小限制
  3. 错误处理:在实际应用中应添加适当的异常处理
  4. 依赖库:需要安装PIL/Pillow库用于图片处理:pip install Pillow
  5. 内存占用:处理大图片时注意内存使用情况

完整示例

python
import base64
import io
import requests
from PIL import Image

def image_base64_converter():
    """图片与Base64相互转换的完整示例"""
    
    # 1. 本地图片转Base64
    def local_to_base64(image_path):
        with open(image_path, "rb") as f:
            return base64.b64encode(f.read()).decode("utf-8")
    
    # 2. 网络图片转Base64
    def url_to_base64(url):
        response = requests.get(url)
        return base64.b64encode(response.content).decode("utf-8")
    
    # 3. Base64转图片文件
    def base64_to_file(base64_str, output_path):
        with open(output_path, "wb") as f:
            f.write(base64.b64decode(base64_str))
    
    # 4. Base64转PIL Image对象
    def base64_to_image(base64_str):
        return Image.open(io.BytesIO(base64.b64decode(base64_str)))
    
    # 使用示例
    # base64_data = local_to_base64("input.jpg")
    # base64_to_file(base64_data, "output.jpg")
    # img = base64_to_image(base64_data)
    # img.show()

# 调用示例函数
# image_base64_converter()

一个 Key 用全球大模型