登录/注册
图片生成 API
概述
海鲸AI 提供统一的图片生成 API 接口,支持 Flux 和 Nano Banana 两个强大的 AI 图像生成模型。通过简单的 HTTP 请求,您可以使用文字描述生成精致、高质量的图片,适用于内容创作、广告设计、产品原型等多种场景。
API 端点
POST https://api.atalk-ai.com/images/generate请求格式
请求头
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
| Content-Type | string | 是 | 固定为 application/json |
| Authorization | string | 是 | API_KEY |
请求参数
以下是完整的 TypeScript 类型定义:
ts
type ImageGenerationRequest = {
// 必填参数
model: string // 模型名称,如 "flux-2-pro"
prompt: string // 图像描述文本
// 通用可选参数
aspect_ratio?: string // 图像宽高比,默认 "1:1"
// 支持: "1:1", "2:3", "3:2", "3:4", "4:5", "5:4", "9:16", "16:9", "21:9"
input_image?: string // 参考图像(Base64 或 URL),最大 20MB 或 20MP
input_image_2?: string // 额外参考图像 2
input_image_3?: string // 额外参考图像 3
input_image_4?: string // 额外参考图像 4
input_image_5?: string // 额外参考图像 5
input_image_6?: string // 额外参考图像 6
input_image_7?: string // 额外参考图像 7
input_image_8?: string // 额外参考图像 8
width?: number | null // 输出宽度(像素),必须是 16 的倍数
height?: number | null // 输出高度(像素),必须是 16 的倍数
seed?: number | null // 随机种子,用于可复现的生成
safety_tolerance?: number // 内容审核级别 (0-5),默认 2
output_format?: 'jpeg' | 'png' // 输出格式,默认 "jpeg"
}参数说明
model (必填)
- 类型:
string - 说明: 要使用的图像生成模型名称
- 示例:
"flux-2-pro","gemini-2.5-flash-image"
prompt (必填)
- 类型:
string - 说明: 描述您想要生成的图像内容,支持中英文
- 建议:
- 尽可能详细地描述图像的主题、风格、色彩、构图等要素
- 可以包含艺术风格、光照效果、视角等细节
- 示例:
"一只可爱的小猫在阳光下玩耍,摄影风格,柔和光线""futuristic city skyline at sunset, cyberpunk style, neon lights"
aspect_ratio (可选)
- 类型:
string - 默认值:
"1:1" - 说明: 图像的宽高比
- 支持的比例:
"1:1"- 正方形,适用于头像、图标"2:3"- 竖版,适用于手机壁纸、海报"3:2"- 横版,适用于风景照、横幅"3:4"- 竖版,适用于 Instagram 竖屏"4:5"- 竖版,适用于社交媒体内容"5:4"- 横版,适用于演示文稿"9:16"- 竖屏,适用于手机全屏、Stories"16:9"- 宽屏,适用于视频封面、电脑壁纸"21:9"- 超宽屏,适用于电影画幅
input_image (可选)
- 类型:
string - 说明: 参考图像,用于图像到图像的生成或编辑
- 格式: Base64 编码的图片数据或图片 URL
- 限制:
- 最大文件大小:20MB
- 示例:
"https://example.com/reference.jpg"或 Base64 字符串
input_image_2 至 input_image_8 (可选)
- 类型:
string - 说明: 额外的参考图像,用于多参考图像编辑
- 数量限制: API 最多支持 8 张图片(1 张主图 + 7 张额外图片)
- 推荐: 建议最多使用 6 张图片以获得最佳效果
- 格式要求: 与
input_image相同
Flux 模型专用参数
以下参数仅在使用 Flux 系列模型时支持(如 flux-2-pro、flux-1.1-pro 等)。
width (可选)
- 类型:
number | null - 默认值:
null(根据 aspect_ratio 自动计算) - 说明: 输出图像的宽度(像素)
- 限制: 必须是 16 的倍数
- 用途: 自定义输出图像的宽度,与 height 配合使用可实现精确的尺寸控制
- 注意: 如果同时指定了 width、height 和 aspect_ratio,width 和 height 会覆盖 aspect_ratio
height (可选)
- 类型:
number | null - 默认值:
null(根据 aspect_ratio 自动计算) - 说明: 输出图像的高度(像素)
- 限制: 必须是 16 的倍数
- 用途: 自定义输出图像的高度,与 width 配合使用可实现精确的尺寸控制
- 注意: 如果同时指定了 width、height 和 aspect_ratio,width 和 height 会覆盖 aspect_ratio
seed (可选)
- 类型:
number | null - 默认值:
null(使用随机种子) - 说明: 随机种子,用于生成可复现的结果
- 范围: 任意整数
- 用途: 使用相同的 seed 和参数可以生成相同的图片
- 示例:
42、12345
safety_tolerance (可选)
- 类型:
number - 默认值:
2 - 说明: 内容审核的宽松程度
- 范围:
0(最严格)到5(最宽松) - 影响: 控制对输入提示词和输出图像的审核强度
output_format (可选)
- 类型:
string - 默认值:
"jpeg" - 说明: 输出图像的格式
- 可选值:
"jpeg"- JPEG 格式(较小文件大小)"png"- PNG 格式(无损压缩)
请求示例
基础文生图示例
bash
curl https://api.atalk-ai.com/images/generate \
-H "Content-Type: application/json" \
-H "Authorization: YOUR_API_KEY" \
-d '{
"model": "flux-2-pro",
"prompt": "一只可爱的小猫在阳光下玩耍,摄影风格,柔和光线",
"aspect_ratio": "16:9"
}'python
import requests
api_url = "https://api.atalk-ai.com/images/generate"
api_key = "YOUR_API_KEY"
payload = {
"model": "flux-2-pro",
"prompt": "一只可爱的小猫在阳光下玩耍,摄影风格,柔和光线",
"aspect_ratio": "16:9"
}
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
response = requests.post(api_url, json=payload, headers=headers)
result = response.json()
if result.get("code") == 0:
images = result.get("data", [])
for image in images:
print(f"图片 URL: {image.get('image')}")javascript
const apiUrl = 'https://api.atalk-ai.com/images/generate'
const apiKey = 'YOUR_API_KEY'
const payload = {
model: 'flux-2-pro',
prompt: '一只可爱的小猫在阳光下玩耍,摄影风格,柔和光线',
aspect_ratio: '16:9',
}
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(payload),
})
const result = await response.json()
if (result.code === 0) {
const images = result.data || []
images.forEach((data) => {
console.log('图片 URL:', data.image)
})
}使用 Flux 高级参数示例(图生图 + 自定义尺寸)
bash
curl https://api.atalk-ai.com/images/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "flux-2-pro",
"prompt": "将这张照片转换为水彩画风格,保持原构图",
"input_image": "https://example.com/input.jpg",
"aspect_ratio": "2:3",
"seed": 42,
"output_format": "png",
"safety_tolerance": 3
}'使用多参考图像:
bash
curl https://api.atalk-ai.com/images/generate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"model": "flux-2-pro",
"prompt": "结合这些参考图像的风格创作一幅新作品",
"input_image": "https://example.com/ref1.jpg",
"input_image_2": "https://example.com/ref2.jpg",
"input_image_3": "https://example.com/ref3.jpg",
"aspect_ratio": "16:9"
}'响应格式
成功响应
当请求成功时,API 返回以下格式的 JSON 数据:
ts
type ImageGenerationResponse = {
code: number // 状态码,0 表示成功,-1 表示失败
data: ImageObject[] // 生成的图片数组
model: string // 实际使用的模型名称
provider: string // 服务提供商名称 (flux, gemini, dalle, etc.)
usage: UsageInfo // 使用统计信息
}
// 图片对象类型(URL 格式 - 如 Flux)
type URLImageObject = {
type: 'url' // 图片类型为 URL
image: string // 图片的 URL 地址
mimeType: null // MIME 类型(URL 类型为 null)
revised_prompt: string | null // 优化后的提示词(部分模型支持)
}
// 图片对象类型(Base64 格式 - 如 Gemini)
type Base64ImageObject = {
type: 'base64' // 图片类型为 Base64
image: string // Base64 编码的图片数据
mimeType: string // MIME 类型,如 "image/png"、"image/jpeg"
revised_prompt: null // Base64 格式不包含优化提示词
}
type ImageObject = URLImageObject | Base64ImageObject
type UsageInfo = {
cost?: number // 本次请求的费用
images_generated?: number // 成功生成的图片数量
images_failed?: number // 失败的图片数量
}响应示例
URL 格式图片(Flux 等模型)
json
{
"code": 0,
"data": [
{
"type": "url",
"image": "https://example.com/generated-image.png",
"mimeType": null,
"revised_prompt": "A cute kitten playing in sunlight, photography style, soft lighting"
}
],
"model": "flux-2-pro",
"provider": "flux",
"usage": {
"cost": 0.04,
"images_generated": 1,
"images_failed": 0
}
}Base64 格式图片(Gemini 等模型)
json
{
"code": 0,
"data": [
{
"type": "base64",
"image": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
"mimeType": "image/png",
"revised_prompt": null
}
],
"model": "gemini-2.5-flash-image",
"provider": "gemini",
"usage": {
"cost": 0.02,
"images_generated": 1,
"images_failed": 0
}
}响应字段说明
code
- 类型:
number - 说明: 请求状态码
0- 成功-1- 失败(具体错误信息见下方错误处理章节)
data
- 类型:
ImageObject[] - 说明: 生成的图片对象数组,根据模型不同返回不同格式
URL 格式(type: "url"):
type- 固定为"url"image- 图片的完整 URL 地址,可直接在浏览器访问或下载mimeType- 固定为nullrevised_prompt- 某些模型会对提示词进行优化,优化后的提示词会在此字段返回;若无优化则为null
Base64 格式(type: "base64"):
type- 固定为"base64"image- Base64 编码的图片数据,需要解码后使用mimeType- 图片的 MIME 类型,如"image/png"、"image/jpeg"revised_prompt- 固定为null
model
- 类型:
string - 说明: 实际使用的模型名称
provider
- 类型:
string - 说明: 服务提供商名称,如
"flux"、"gemini"、"dalle"等
usage
- 类型:
UsageInfo - 说明: 使用统计信息
- 可选字段:
cost- 本次请求的费用(单位:人民币元)images_generated- 成功生成的图片数量images_failed- 失败的图片数量
错误处理
错误响应格式
当请求失败时,API 返回以下格式:
ts
type ErrorResponse = {
code: -1 // 错误时固定为 -1
msg: string // 错误描述信息
}错误响应示例:
json
{
"code": -1,
"msg": "Invalid aspect_ratio parameter. Supported ratios: 1:1, 2:3, 3:2, 3:4, 4:5, 5:4, 9:16, 16:9, 21:9"
}json
{
"code": -1,
"msg": "API key is invalid or expired"
}最佳实践
1. 优化提示词
具体描述:提供详细的场景、主体、风格描述
✅ 好的提示词:
"一只橘色的小猫坐在木质窗台上,背景是落日余晖,温暖的光线从侧面照射,电影般的景深效果"
❌ 不好的提示词:
"猫"包含风格关键词:添加艺术风格、摄影风格等关键词
- "油画风格"、"水彩画"、"赛博朋克风格"
- "电影级光照"、"柔和光线"、"戏剧性光影"
- "广角镜头"、"微距摄影"、"鸟瞰视角"2. 选择合适的宽高比
根据实际用途选择合适的 aspect_ratio:
- 社交媒体:
4:5(Instagram Feed)、9:16(Stories、Reels) - 网站横幅:
16:9、21:9 - 海报/印刷:
2:3、3:4 - 图标/头像:
1:1
3. 错误重试策略
实现指数退避的重试机制:
python
import time
def generate_image_with_retry(payload, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.post(api_url, json=payload, headers=headers)
result = response.json()
if result.get("code") == 0:
return result
elif result.get("code") in [429, 500, 503]:
# 可重试的错误
wait_time = (2 ** attempt) + 1 # 指数退避
time.sleep(wait_time)
continue
else:
# 不可重试的错误
return result
except Exception as e:
if attempt == max_retries - 1:
raise
time.sleep(2 ** attempt)
return {"code": -1, "message": "Max retries exceeded"}4. 图片处理与存储
根据不同的图片格式(URL 或 Base64),使用不同的处理方式:
处理 URL 格式图片
生成的图片 URL 通常有时效性,建议及时下载并存储:
python
import requests
def download_image_from_url(url: str, save_path: str):
"""从 URL 下载图片到本地"""
response = requests.get(url, stream=True)
response.raise_for_status()
with open(save_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"图片已保存到: {save_path}")处理 Base64 格式图片
某些模型返回 Base64 编码的图片数据:
python
import base64
def save_base64_image(base64_data: str, save_path: str):
"""保存 Base64 编码的图片"""
# 解码 Base64 数据
image_bytes = base64.b64decode(base64_data)
# 写入文件
with open(save_path, 'wb') as f:
f.write(image_bytes)
print(f"图片已保存到: {save_path}")统一处理函数
python
def save_image(image_obj: dict, save_path: str):
"""根据图片类型自动选择保存方式"""
image_type = image_obj.get("type")
if image_type == "url":
# URL 格式:下载图片
url = image_obj.get("image")
download_image_from_url(url, save_path)
elif image_type == "base64":
# Base64 格式:解码并保存
base64_data = image_obj.get("image")
save_base64_image(base64_data, save_path)
else:
raise ValueError(f"Unsupported image type: {image_type}")
# 使用示例
result = generate_image(payload)
if result.get("code") == 0:
images = result.get("data", [])
for i, image in enumerate(images):
# 根据 mimeType 确定文件扩展名
mime_type = image.get("mimeType")
ext = "png" # 默认
if mime_type == "image/jpeg":
ext = "jpg"
elif mime_type == "image/png":
ext = "png"
save_image(image, f"generated_image_{i}.{ext}")JavaScript 处理示例
javascript
// 处理 URL 格式图片
async function downloadImage(url, filename) {
const response = await fetch(url)
const blob = await response.blob()
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = filename
link.click()
URL.revokeObjectURL(link.href)
}
// 处理 Base64 格式图片
function saveBase64Image(base64Data, mimeType, filename) {
const link = document.createElement('a')
link.href = `data:${mimeType};base64,${base64Data}`
link.download = filename
link.click()
}
// 统一处理函数
async function saveImage(imageObj, filename) {
if (imageObj.type === 'url') {
await downloadImage(imageObj.image, filename)
} else if (imageObj.type === 'base64') {
saveBase64Image(imageObj.image, imageObj.mimeType, filename)
}
}
// 使用示例
const result = await generateImage()
if (result.code === 0) {
result.data.forEach((image, index) => {
const ext = image.mimeType === 'image/jpeg' ? 'jpg' : 'png'
saveImage(image, `generated_image_${index}.${ext}`)
})
}支持的模型
查看 模型列表页面 获取所有支持的图像生成模型及其详细信息,包括:
- 模型能力特点
- 价格信息
- 支持的参数
- 最佳实践建议
相关资源
技术支持
如有任何问题或需要技术支持,请通过以下方式联系我们: