> ## Documentation Index
> Fetch the complete documentation index at: https://docs.venice.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 图像生成

> 使用 Venice 原生图像 API 或 OpenAI 兼容的 images 端点，从文本 prompt 生成图像，支持风格控制以及二进制或 base64 输出。

Venice 上的图像生成是同步的。将 prompt 发送到 `/image/generate`，并在同一响应中收到您的图像，可以是 JSON 中的 base64，或在 `return_binary` 为 `true` 时为原始二进制。

## 端点

| 端点                         | 用途                 | 何时使用                    |
| -------------------------- | ------------------ | ----------------------- |
| `POST /image/generate`     | Venice 原生图像生成 API  | 用于完整功能支持                |
| `GET /image/styles`        | 列出可用的风格预设          | 在发送 `style_preset` 之前使用 |
| `POST /images/generations` | OpenAI 兼容的图像生成 API | 迁移现有 OpenAI 图像客户端时使用    |

## 第 1 步：发送生成请求

尺寸是模型专属的。某些模型接受显式的 `width` 和 `height`；某些公开 `aspect_ratio`；分辨率分级模型公开 `aspect_ratio` 加上 `resolution` 值（如 `1K`、`2K` 或 `4K`）。

**基于像素的尺寸示例：**

```bash theme={"system"}
POST https://api.venice.ai/api/v1/image/generate
Authorization: Bearer $VENICE_API_KEY
Content-Type: application/json

{
  "model": "venice-sd35",
  "prompt": "A cinematic photo of a gondola passing through a narrow Venice canal at blue hour, warm window lights reflecting on the water",
  "negative_prompt": "blurry, low quality, distorted anatomy, text, watermark",
  "width": 1024,
  "height": 1024,
  "format": "webp"
}
```

**基于宽高比的尺寸示例：**

```bash theme={"system"}
POST https://api.venice.ai/api/v1/image/generate
Authorization: Bearer $VENICE_API_KEY
Content-Type: application/json

{
  "model": "qwen-image-2",
  "prompt": "A cinematic photo of a gondola passing through a narrow Venice canal at blue hour",
  "aspect_ratio": "16:9",
  "format": "webp"
}
```

**基于分辨率等级的尺寸示例：**

```bash theme={"system"}
POST https://api.venice.ai/api/v1/image/generate
Authorization: Bearer $VENICE_API_KEY
Content-Type: application/json

{
  "model": "gpt-image-2",
  "prompt": "A cinematic wide shot of a gondola passing through a narrow Venice canal at blue hour",
  "aspect_ratio": "16:9",
  "resolution": "4K",
  "format": "png"
}
```

相同模式也适用于其他分辨率分级模型：

```json theme={"system"}
{
  "model": "nano-banana-pro",
  "prompt": "A serene canal in Venice at sunset",
  "aspect_ratio": "16:9",
  "resolution": "2K"
}
```

使用[图像模型](/models/image)或 [Models API](/api-reference/endpoint/models/list) 确认每个模型接受哪些尺寸字段。

**响应（200）：**

```json theme={"system"}
{
  "id": "generate-image-1234567890",
  "images": [
    "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoQABAAPm..."
  ],
  "timing": {
    "inferenceDuration": 1840,
    "inferencePreprocessingTime": 22,
    "inferenceQueueTime": 31,
    "total": 1893
  }
}
```

`images` 数组包含 base64 编码的图像数据。解码第一项以保存或显示。`timing.total` 是完整的请求时长（毫秒）。

## 第 2 步：解码并保存图像

<CodeGroup>
  ```python Python theme={"system"}
  import base64
  import os
  import requests

  response = requests.post(
      "https://api.venice.ai/api/v1/image/generate",
      headers={
          "Authorization": f"Bearer {os.environ['VENICE_API_KEY']}",
          "Content-Type": "application/json",
      },
      json={
          "model": "venice-sd35",
          "prompt": "A cinematic photo of a gondola passing through a narrow Venice canal at blue hour, warm window lights reflecting on the water",
          "width": 1024,
          "height": 1024,
          "format": "webp",
      },
  )

  data = response.json()
  image_bytes = base64.b64decode(data["images"][0])

  with open("output.webp", "wb") as f:
      f.write(image_bytes)

  print(f"Saved image from request {data['id']}")
  ```

  ```javascript Node.js theme={"system"}
  import fs from "fs";

  const response = await fetch("https://api.venice.ai/api/v1/image/generate", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.VENICE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "venice-sd35",
      prompt: "A cinematic photo of a gondola passing through a narrow Venice canal at blue hour, warm window lights reflecting on the water",
      width: 1024,
      height: 1024,
      format: "webp",
    }),
  });

  const data = await response.json();
  const imageBuffer = Buffer.from(data.images[0], "base64");
  fs.writeFileSync("output.webp", imageBuffer);

  console.log(`Saved image from request ${data.id}`);
  ```
</CodeGroup>

## 第 3 步：返回二进制而非 JSON（可选）

如果您希望响应体本身就是图像文件，请设置 `return_binary: true`。当您希望直接流式传输或保存图像而不进行 base64 解码时，这非常有用。

```bash theme={"system"}
curl https://api.venice.ai/api/v1/image/generate \
  -H "Authorization: Bearer $VENICE_API_KEY" \
  -H "Content-Type: application/json" \
  -o output.png \
  -d '{
    "model": "qwen-image-2",
    "prompt": "Minimalist poster of a moonlit Venetian bridge in deep blue tones",
    "format": "png",
    "return_binary": true
  }'
```

当 `return_binary` 为 `true` 时，响应体根据您请求的 `format` 是原始 `image/jpeg`、`image/png` 或 `image/webp` 数据。

<Note>
  仅当 `return_binary` 为 `false` 时才支持 `variants`。
</Note>

***

## 第 4 步：列出可用图像风格（可选）

如果您想使用 `style_preset`，请先从 `/image/styles` 获取可用风格：

```bash theme={"system"}
curl https://api.venice.ai/api/v1/image/styles \
  -H "Authorization: Bearer $VENICE_API_KEY"
```

**响应（200）：**

```json theme={"system"}
[
  "3D Model",
  "Analog Film",
  "Anime",
  "Cinematic",
  "Digital Art"
]
```

然后将其中一个值传入您的生成请求：

```json theme={"system"}
{
  "model": "qwen-image-2",
  "prompt": "A futuristic Venice skyline at sunrise",
  "style_preset": "Cinematic"
}
```

当您想要确切的预设名称而非猜测时，请使用 styles 端点。

***

## 请求参数

| 参数                  | 类型      | 必填 | 默认      | 说明                                                                                 |
| ------------------- | ------- | -- | ------- | ---------------------------------------------------------------------------------- |
| `model`             | string  | 是  | -       | 用于生成的模型 ID                                                                         |
| `prompt`            | string  | 是  | -       | 要生成的内容                                                                             |
| `negative_prompt`   | string  | 否  | -       | 在图像中要避免的内容                                                                         |
| `width`             | integer | 否  | `1024`  | 基于像素的模型（如 `venice-sd35` 和 `qwen-image`）的输出宽度（像素）                                   |
| `height`            | integer | 否  | `1024`  | 基于像素的模型（如 `venice-sd35` 和 `qwen-image`）的输出高度（像素）                                   |
| `format`            | string  | 否  | `webp`  | 输出格式：`jpeg`、`png` 或 `webp`                                                         |
| `variants`          | integer | 否  | `1`     | 要生成的图像数（`1`-`4`），仅当 `return_binary` 为 `false` 时                                    |
| `return_binary`     | boolean | 否  | `false` | 返回原始图像字节而非 base64 JSON                                                             |
| `safe_mode`         | boolean | 否  | `true`  | 启用时模糊成人内容                                                                          |
| `seed`              | integer | 否  | 随机      | 重用相同 seed 以实现更一致的迭代                                                                |
| `cfg_scale`         | number  | 否  | 模型相关    | 较高值推动模型更紧密地遵循 prompt                                                               |
| `style_preset`      | string  | 否  | -       | 从[图像风格](/api-reference/endpoint/image/styles)应用预设风格                                |
| `aspect_ratio`      | string  | 条件 | -       | 由支持基于比例尺寸的模型使用，例如 `qwen-image-2`、`gpt-image-2`、`nano-banana-2` 和 `nano-banana-pro` |
| `resolution`        | string  | 条件 | -       | 由支持分辨率分级（如 `1K`、`2K` 或 `4K`）的模型使用                                                  |
| `enable_web_search` | boolean | 条件 | `false` | 允许支持的模型使用当前 web 信息；产生额外费用                                                          |

验证是模型专属的。在跨多个模型依赖某个参数之前，请查看[图像模型](/models/image)和 [Models API](/api-reference/endpoint/models/list)。

***

## 模型专属选项

### 高分辨率生成

某些图像模型支持 `aspect_ratio` 但没有可选的 `resolution` 等级。例如，`qwen-image-2` 接受宽高比并映射到模型专属的输出尺寸：

```json theme={"system"}
{
  "model": "qwen-image-2",
  "prompt": "Editorial product photo of a luxury watch on black marble, dramatic studio lighting",
  "aspect_ratio": "16:9"
}
```

其他图像模型支持 `aspect_ratio` 加上 `resolution` 等级。例如，`gpt-image-2`、`nano-banana-2` 和 `nano-banana-pro` 支持 `1K`、`2K` 和 `4K`：

```json theme={"system"}
{
  "model": "gpt-image-2",
  "prompt": "Editorial product photo of a luxury watch on black marble, dramatic studio lighting",
  "aspect_ratio": "16:9",
  "resolution": "4K"
}
```

```json theme={"system"}
{
  "model": "nano-banana-2",
  "prompt": "Editorial product photo of a luxury watch on black marble, dramatic studio lighting",
  "aspect_ratio": "16:9",
  "resolution": "2K"
}
```

使用[图像模型](/models/image)查看哪些模型支持更高分辨率及其定价。

### 风格预设

如果所选模型支持，`style_preset` 让您可以在不重写整个 prompt 的情况下引导输出。您可以从[图像风格](/api-reference/endpoint/image/styles)获取有效的预设名称：

```json theme={"system"}
{
  "model": "qwen-image-2",
  "prompt": "A futuristic Venice skyline at sunrise",
  "style_preset": "3D Model"
}
```

当前风格列表请参阅[图像风格](/api-reference/endpoint/image/styles)。

***

## OpenAI 兼容端点

如果您已在使用 OpenAI 图像 SDK 或现有的 DALL-E 集成，Venice 也支持 `POST /images/generations`。它提供更简单的请求格式，但功能比 Venice 原生端点少。

**请求：**

```json theme={"system"}
{
  "model": "qwen-image-2",
  "prompt": "A clean isometric illustration of an AI control room",
  "size": "1024x1024",
  "response_format": "b64_json"
}
```

使用 OpenAI 兼容路由可加快迁移。当您需要 Venice 专属选项（如 `cfg_scale`、`style_preset`、`variants` 或二进制响应）时，请使用 `/image/generate`。

***

## Prompt 编写技巧

1. 先写主体，然后添加媒介、灯光、构图和情绪。
2. 把必须避免的细节放入 `negative_prompt`，而不是过载主 prompt。
3. 迭代时重用 `seed`，以便在不完全改变构图的情况下比较 prompt 改动。
4. 让尺寸感知模型。某些模型使用 `width`/`height`，某些使用 `aspect_ratio`，分辨率分级模型使用 `aspect_ratio` 加 `resolution`。
5. 在探索阶段使用 `variants`，方向锁定后切回单一输出。

***

## 错误

| 状态    | 含义                 | 应对方式                                                          |
| ----- | ------------------ | ------------------------------------------------------------- |
| `400` | 请求参数无效             | 检查字段名、类型和模型专属约束                                               |
| `401` | 身份验证失败，或模型需要更高访问等级 | 检查 API 密钥和模型访问权限                                              |
| `402` | 余额不足               | 在 [venice.ai/settings/api](https://venice.ai/settings/api) 充值 |
| `415` | 内容类型无效             | 使用 `Content-Type: application/json` 发送 JSON                   |
| `429` | 速率限制超出或模型过载        | 使用退避重试；查看 `Retry-After` 请求头                                   |
| `500` | 推理处理失败             | 重试请求                                                          |
| `503` | 模型容量已满             | 短暂延迟后重试                                                       |

<Note>
  启用 Safe Venice 时，如果您需要以编程方式检测审核结果，请检查响应头，例如 `x-venice-is-blurred` 和 `x-venice-is-content-violation`。
</Note>

***

## 可用模型

请参阅[图像模型](/models/image)了解当前模型列表、定价和功能支持。
