跳转至

图片生成

YUNiversity API 提供 OpenAI 兼容的文字生图接口: POST /v1/images/generations。请求会按所选模型分发到可用的图片通道, 因此实际支持的尺寸、质量和可选字段以当前模型为准。

最小请求

先用 GET /v1/models 确认账号当前可用的图片模型。下面以 gpt-image-2 为例;如果列表中没有该模型,请替换为列表中的图片模型。

curl https://api.yuniversity.cc/v1/images/generations \
  -H "Authorization: Bearer <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "一间有落地窗的安静书房,柔和的晨光,写实风格",
    "size": "1024x1024"
  }'

PowerShell 中可使用 curl.exe,避免被 PowerShell 的命令别名替换:

$headers = @{
  Authorization = "Bearer $env:YUNIVERSITY_API_KEY"
  "Content-Type" = "application/json"
}
$body = @{
  model = "gpt-image-2"
  prompt = "一间有落地窗的安静书房,柔和的晨光,写实风格"
  size = "1024x1024"
} | ConvertTo-Json

Invoke-RestMethod https://api.yuniversity.cc/v1/images/generations `
  -Method Post -Headers $headers -Body $body

Python 与 JavaScript

以下示例只发送请求,不包含真实密钥,也不会在文档测试中调用付费模型。

import json
import os
from urllib.request import Request, urlopen

request = Request(
    "https://api.yuniversity.cc/v1/images/generations",
    data=json.dumps({
        "model": "gpt-image-2",
        "prompt": "一间有落地窗的安静书房,柔和的晨光,写实风格",
        "size": "1024x1024",
    }).encode(),
    headers={
        "Authorization": f"Bearer {os.environ['YUNIVERSITY_API_KEY']}",
        "Content-Type": "application/json",
    },
    method="POST",
)
with urlopen(request) as response:
    result = json.load(response)
print(result["data"])
const response = await fetch("https://api.yuniversity.cc/v1/images/generations", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.YUNIVERSITY_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-image-2",
    prompt: "一间有落地窗的安静书房,柔和的晨光,写实风格",
    size: "1024x1024",
  }),
});
if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`);
console.log(await response.json());

常用参数

字段 类型 说明
model string 图片模型 ID,建议先从 /v1/models 获取。
prompt string 必填的图像描述。
n integer 生成数量;未提供时通常为 1,且服务端限制最大值为 128。
size string 目标尺寸,例如 1024x1024;可选值由模型和通道决定。
quality string 质量档位;仅在当前模型支持时使用。
response_format string 请求 URL 或 base64 结果(如果当前模型支持该选择)。

backgroundoutput_formatmoderationwatermark 等字段可能被某些 模型接受,但并非所有通道都支持。不要把一个模型的参数直接套用到另一个 模型;收到 400 时先删除可选字段,再按模型列表和错误信息调整。

响应结果

服务端返回 data 数组。通道可以返回可下载的 URL(字段为 url):

URL 结果

{
  "created": 1760000000,
  "data": [
    {
      "url": "https://example.invalid/generated-image.png",
      "revised_prompt": "一间有落地窗的安静书房,柔和的晨光,写实风格"
    }
  ]
}

也可以返回 base64 结果(字段为 b64_json):

base64 结果

{
  "created": 1760000000,
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB",
      "revised_prompt": "一间有落地窗的安静书房,柔和的晨光,写实风格"
    }
  ]
}

url 是临时结果地址,拿到后应尽快下载并自行保存;b64_json 是图片内容 的 base64 字符串,客户端需要解码后写入文件。一个响应可能只有其中一种 结果,也可能同时包含两种结果;读取时分别判断字段是否存在。

不支持的接口

POST /v1/images/variationsrc.37 中明确标记为未实现,不要用它替代 图片生成接口。需要图生图或编辑时,先确认当前模型和通道是否支持相应的 imagesmask 或编辑字段。