1. 主要多模态模型的图片返回格式
不同的API设计理念导致了返回格式的多样化,主要可以分为三大类:直接返回图片URL、返回Base64编码数据,以及返回包含图片数据的JSON对象。
| 模型/服务 | 典型返回格式 | 说明 |
|---|---|---|
| Nano Banana (Gemini 2.5 Flash Image) | inline_data (二进制) 或 image_url[ |
响应可能包含 inline_data 字段,内含原始图像字节;也可能通过 image_url 提供访问链接。 |
| OpenAI DALL·E 3 | JSON对象中的图片URL (url) 或Base64字符串 (b64_json) |
响应结构为 response.data[0].url 或 response.data[0].b64_json,URL链接通常在生成后一小时内有效。 |
| Google Gemini (Vision/Image) | parts 中的 inline_data 或 url |
生成的图像可能以 inline_data 内嵌二进制数据,或以 url 形式返回。 |
| Stability AI / Stable Diffusion | JSON对象中的Base64字符串 (base64) |
API返回值通常是JSON格式,图片数据存储在 artifacts[0].base64 或 image 字段中。 |
| Midjourney (API) | 异步任务ID,完成后返回图片URL | 由于生成过程耗时,请求通常先返回 task_id,完成后通过回调或查询接口获取最终图片URL。 |
2. 后续处理详细实例
无论何种格式,处理流程通常遵循:提取数据 → 解码/下载 → 保存/显示。以下是几个通用示例。
示例1:处理直接返回的图片URL
如果你的API响应像DALL·E或部分Midjourney结果那样,直接给出了图片的URL,通常需要使用 requests 库来下载它。
python
import requests
# 假设从响应中提取到了URL
image_url = response.data[0].url # OpenAI DALL·E 示例[[22]]
# image_url = response.images[0]["image_url"]["url"] # 类似Nano Banana格式
# 下载图片
image_data = requests.get(image_url).content
# 保存为本地文件
with open('generated_image.png', 'wb') as f:
f.write(image_data)
print("图片已保存。")
示例2:处理Base64编码的图片数据
对于Stability AI或可选的DALL·E b64_json 返回格式,你需要解码Base64字符串。
python
import base64
from PIL import Image
from io import BytesIO
# 假设从响应中提取到Base64字符串(注意去除可能存在的Data URL前缀)
b64_string = response.artifacts[0].base64 # Stability AI 示例[[23]]
# 或 response.data[0].b64_json # OpenAI DALL·E 示例[[24]]
# 如果是 "data:image/png;base64,..." 格式,需要先分割
if b64_string.startswith('data:'):
b64_string = b64_string.split(',', 1)[1]
# 解码并保存
image_data = base64.b64decode(b64_string)
image = Image.open(BytesIO(image_data))
image.save('generated_image.jpg')
print("Base64图片已解码并保存。")
示例3:处理内联二进制数据(如Nano Banana/Gemini)
一些API(如Nano Banana)可能在响应中直接包含图像的二进制数据块。
python
from PIL import Image
from io import BytesIO
# 假设响应结构如 part.inline_data.data[[25]]
image_bytes = response.candidates[0].content.parts[0].inline_data.data
# 直接使用字节数据
image = Image.open(BytesIO(image_bytes))
image.save('generated_image.png')
print("二进制图片数据已保存。")
示例4:处理异步任务(如Midjourney)
对于Midjourney这类异步API,处理流程稍复杂,需要轮询或等待回调。
python
import time
import requests
# 1. 提交任务,获取任务ID
submit_response = requests.post('https://api.midjourney.example/submit', json={'prompt': 'a cat'})
task_id = submit_response.json()['task_id'] # 假设返回格式[[27]]
# 2. 轮询查询结果
while True:
query_response = requests.get(f'https://api.midjourney.example/query?result={task_id}')
result = query_response.json()
if result['status'] == 'completed':
# 3. 任务完成,获取图片URL并下载
image_url = result['image_url']
image_data = requests.get(image_url).content
with open('midjourney_result.png', 'wb') as f:
f.write(image_data)
print("异步任务图片已保存。")
break
elif result['status'] == 'failed':
print("任务失败:", result.get('error'))
break
else:
print("任务处理中,等待...")
time.sleep(5) # 等待5秒后再次查询
总结
不同多模态模型的图片返回格式各有特点,需要根据具体API的文档,从响应中正确提取出图片URL 、Base64字符串 或二进制数据,然后选择对应的下载或解码方法来处理。在处理异步生成任务时,还需要设计轮询或回调机制来获取最终结果。