You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将API返回的request.content转换为可读取图片并保存?

解决方法

API返回的并非直接的图片字节,而是包含<img>标签的HTML内容,其中src属性是Data URI格式(包含Base64编码的图片数据)。需要按以下步骤处理:

1. 提取Base64编码的图片数据

先将响应的字节内容转为字符串,再通过正则匹配提取Data URI中的Base64部分:

import re
import requests
import base64

# 发起请求(保持你的原有代码)
r = requests.get(urlGetPhoto, headers=h, stream=True)
# 字节转字符串
response_content = r.content.decode('utf-8')

# 正则匹配Data URI中的图片格式和Base64数据
pattern = r'data:image/(\w+);base64,([^"]+)'
match_result = re.search(pattern, response_content)

if not match_result:
    raise ValueError("响应中未找到有效的图片Base64数据")

image_ext = match_result.group(1)  # 获取图片格式(如jpg、png)
base64_str = match_result.group(2) # 获取纯Base64编码字符串

2. 解码Base64为图片字节

使用base64.b64decode将编码字符串还原为原始图片字节:

try:
    image_bytes = base64.b64decode(base64_str)
except base64.binascii.Error as e:
    raise ValueError(f"Base64解码失败: {str(e)}")

3. 保存为本地图片文件

以二进制写入模式打开文件,写入解码后的字节:

with open(f"saved_image.{image_ext}", "wb") as img_file:
    img_file.write(image_bytes)

完整整合代码

import re
import requests
import base64

# 你的请求参数
urlGetPhoto = "你的API地址"
h = {"你的请求头"}

try:
    r = requests.get(urlGetPhoto, headers=h, stream=True)
    r.raise_for_status()  # 检查请求是否成功

    response_content = r.content.decode('utf-8')
    pattern = r'data:image/(\w+);base64,([^"]+)'
    match_result = re.search(pattern, response_content)

    if not match_result:
        print("未找到有效的图片数据")
    else:
        image_ext = match_result.group(1)
        base64_str = match_result.group(2)
        image_bytes = base64.b64decode(base64_str)
        
        with open(f"saved_image.{image_ext}", "wb") as img_file:
            img_file.write(image_bytes)
            print(f"图片已保存为 saved_image.{image_ext}")

except requests.exceptions.RequestException as e:
    print(f"请求失败: {str(e)}")
except ValueError as e:
    print(f"处理错误: {str(e)}")

内容的提问来源于stack exchange,提问作者leogamer2222

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:36:30