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

# 使用 Viggle Image 生成图片

> 根据文字提示词生成 1–6 张 PNG 图片，可选用最多 8 张参考图引导，支持 1K 或 2K。

Viggle Image 根据文字提示词生成 PNG 图片。添加参考图可以把某个主体、产品或风格带入结果中。一次请求可按你选定的固定尺寸生成 1 到 6 张图片，并返回一个 `img_` 任务，轮询该任务直到图片就绪即可。可用于角色设定图、[视频生成](https://docs.viggle.ai/zh/v1/video/first-frame-to-video.md)的首帧、缩略图和营销用静态图。

## 参数

必须以 `multipart/form-data` 发送，即使没有参考图也是如此。JSON 或 URL 编码的请求体会以 `400` 拒绝。

| 参数 | 必填 | 默认值 | 取值 |
| - | - | - | - |
| `prompt` | 是 | | 要画的内容，最多 4000 个字符（按 Unicode 码点计算，一个中日韩字符计为一个） |
| `n` | 否 | `1` | 1–6 张图片 |
| `resolution` | 否 | `1K` | `1K` 或 `2K`。决定尺寸档位和价格 |
| `aspect_ratio` | 否 | `1:1` | `1:1`、`16:9`、`9:16`、`4:3`、`3:4`、`3:2`、`2:3` |
| `seed` | 否 | 随机 | 0–2147483647。第 `i` 张图片（从 0 开始）使用 `seed + i`，因此一个 seed 可以复现整组图片 |
| `reference_image` | 否 | | 上传的图片，可重复传入 |
| `reference_image_url` | 否 | | 公开的 `http(s)` 图片 URL，可重复传入 |

参考图总共最多 8 张，文件和 URL 可任意混用。每张不超过 24 MiB，长边与短边之比不超过 8，格式为 JPEG、PNG、WebP、GIF、BMP、TIFF 或 HEIC。模型先读取上传的文件，再读取 URL，各自按你发送的顺序。所有字段详见 [API 参考](https://docs.viggle.ai/zh/v1/api-reference/images/generate-images.md)。

### 输出尺寸

`aspect_ratio` 和 `resolution` 共同确定一个固定尺寸。带参考图时，`2K` 的尺寸会更小，但价格不变。

| `aspect_ratio` | `1K` | `2K` | 带参考图的 `2K` |
| - | - | - | - |
| `1:1` | 1024 × 1024 | 2048 × 2048 | 1536 × 1536 |
| `16:9` | 1376 × 768 | 2720 × 1536 | 2048 × 1152 |
| `9:16` | 768 × 1376 | 1536 × 2720 | 1152 × 2048 |
| `4:3` | 1184 × 896 | 2368 × 1760 | 1760 × 1344 |
| `3:4` | 896 × 1184 | 1760 × 2368 | 1344 × 1760 |
| `3:2` | 1248 × 832 | 2496 × 1664 | 1888 × 1248 |
| `2:3` | 832 × 1248 | 1664 × 2496 | 1248 × 1888 |

## 价格

按张计费：`1K` 每张 1 积分（$0.01），`2K` 每张 2 积分（$0.02）。`aspect_ratio`、`seed` 和参考图不影响价格。

```
cost = n × (1 credit at 1K, or 2 credits at 2K)
```

3 张 `2K` 图片需 6 积分（\$0.06）。创建任务时会预扣全部费用，任务失败则全额退款。

如果余额不足以支付该任务，创建请求会返回 `402 INSUFFICIENT_CREDITS`，错误消息中会注明费用，且任务不会启动。`429 RATE_LIMITED` 表示积分预扣通道繁忙，请退避后重试。

## 生成、等待并下载

下面的脚本请求两张 `1K` 的 `16:9` 图片（2 积分），每 3 秒轮询一次，然后保存 `image_0.png` 和 `image_1.png`。不需要任何输入文件。

```bash cURL theme={null}
#!/usr/bin/env bash
set -euo pipefail
API="https://apis.viggle.ai/v1"
AUTH="Authorization: Bearer $VIGGLE_API_KEY"

image_id=$(curl -sf -X POST "$API/images" -H "$AUTH" \
  -F prompt="A watercolor fox reading a book under a maple tree" \
  -F aspect_ratio=16:9 \
  -F resolution=1K \
  -F n=2 | jq -r '.id')
echo "created $image_id"

while true; do
  job=$(curl -sf "$API/images/$image_id" -H "$AUTH")
  case "$(echo "$job" | jq -r '.status')" in
    ready) break ;;
    failed) echo "failed: $(echo "$job" | jq -c '.error')" >&2; exit 1 ;;
  esac
  sleep 3
done

i=0
for url in $(echo "$job" | jq -r '.images[].url'); do
  curl -sf -o "image_$i.png" "$url"
  echo "saved image_$i.png from $url"
  i=$((i + 1))
done
```

```javascript Node.js theme={null}
import { writeFile } from "node:fs/promises";

const API = "https://apis.viggle.ai/v1";
const headers = { Authorization: `Bearer ${process.env.VIGGLE_API_KEY}` };

async function call(path, init = {}) {
  const res = await fetch(`${API}${path}`, { ...init, headers });
  const body = await res.json();
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${JSON.stringify(body.error)}`);
  return body;
}

const form = new FormData();
form.append("prompt", "A watercolor fox reading a book under a maple tree");
form.append("aspect_ratio", "16:9");
form.append("resolution", "1K");
form.append("n", "2");
let job = await call("/images", { method: "POST", body: form });
console.log(`created ${job.id}`);

while (job.status === "queued" || job.status === "processing") {
  await new Promise((r) => setTimeout(r, 3000));
  job = await call(`/images/${job.id}`);
}
if (job.status !== "ready") throw new Error(`failed: ${JSON.stringify(job.error)}`);

for (const [i, image] of job.images.entries()) {
  const png = await fetch(image.url);
  await writeFile(`image_${i}.png`, Buffer.from(await png.arrayBuffer()));
  console.log(`saved image_${i}.png (${image.width}x${image.height}, seed ${image.seed})`);
}
```

```python Python theme={null}
import os
import time
import requests

API = "https://apis.viggle.ai/v1"
headers = {"Authorization": f"Bearer {os.environ['VIGGLE_API_KEY']}"}

fields = {
    "prompt": "A watercolor fox reading a book under a maple tree",
    "aspect_ratio": "16:9",
    "resolution": "1K",
    "n": "2",
}
# files= makes requests send multipart/form-data, which the endpoint requires.
res = requests.post(
    f"{API}/images",
    headers=headers,
    files={name: (None, value) for name, value in fields.items()},
)
res.raise_for_status()
job = res.json()
print(f"created {job['id']}")

while job["status"] in ("queued", "processing"):
    time.sleep(3)
    res = requests.get(f"{API}/images/{job['id']}", headers=headers)
    res.raise_for_status()
    job = res.json()
if job["status"] != "ready":
    raise RuntimeError(f"failed: {job.get('error')}")

for i, image in enumerate(job["images"]):
    with open(f"image_{i}.png", "wb") as f:
        f.write(requests.get(image["url"]).content)
    print(f"saved image_{i}.png ({image['width']}x{image['height']}, seed {image['seed']})")
```

## 添加参考图

用 `reference_image` 上传文件，用 `reference_image_url` 传入 URL，或两者混用。轮询和下载方式不变。

```bash theme={null}
curl -X POST https://apis.viggle.ai/v1/images \
  -H "Authorization: Bearer $VIGGLE_API_KEY" \
  -F prompt="The same fox, now in winter, snow falling" \
  -F aspect_ratio=1:1 \
  -F resolution=2K \
  -F reference_image=@fox.png \
  -F reference_image_url=https://example.com/style.jpg
```

这会生成一张 1536 × 1536 的图片，费用为 2 积分（\$0.02）。

## 获取结果

创建请求会返回一个 `queued` 状态的任务：

```json theme={null}
{
  "id": "img_b16a190d-2d44-41a0-8056-ef68183c3b9e",
  "status": "queued",
  "model": "viggle-image",
  "progress": 0,
  "images": [],
  "created_at": "2026-11-20T08:20:00Z",
  "completed_at": null,
  "error": null
}
```

每 2–3 秒轮询一次 `GET /v1/images/{image_id}`。每完成一张图片，`progress` 就会增加。当 `status` 为 `ready` 时，`images` 会按顺序列出全部 `n` 张图片，每张都包含 `url`、`width`、`height` 以及所用的 `seed`。一个任务要么生成整组图片，要么整体失败；开始运行后 15 分钟内未完成的任务会失败。

> [!WARNING]
>
> **请立即下载。** 每个 `url` 有效期为 1 小时，每次读取任务都会返回新链接。文件会在任务完成 24 小时后删除；之后读取任务仍显示 `ready`，但每个 `url` 都为 `null`。

只有创建任务的 API 密钥才能读取该任务；其他密钥会收到 `404 NOT_FOUND`。失败的任务带有 `error.code`、`error.message` 和 `error.retryable`。当 `retryable` 为 `true` 时，用相同参数创建新任务即可；否则请先修改提示词或参考图。失败的任务会退款。整个 API 的状态和错误说明见[任务生命周期](https://docs.viggle.ai/zh/v1/concepts/task-lifecycle.md)。

## 后续步骤

> [card] [首帧生视频](https://docs.viggle.ai/zh/v1/video/first-frame-to-video.md)
>
> 用 Viggle H3 让图片动起来。

> [card] [3D 角色](https://docs.viggle.ai/zh/v1/3d/characters.md)
>
> 把角色图变成带骨骼的 3D 角色。

> [card] [API 参考](https://docs.viggle.ai/zh/v1/api-reference/images/get-an-image-job.md)
>
> 完整的图片任务对象及全部错误。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.