Source: https://ailoot.ai/docs/zh-hant-tw/api/images/
Canonical: https://ailoot.ai/docs/zh-hant-tw/api/images/
Language: zh-hant-tw

[API](https://ailoot.ai/docs/zh-hant-tw/) 

# 影像

[Markdown](https://ailoot.ai/docs/zh-hant-tw/api/images/index.md)

以 OpenAI Images 格式生成與編輯影像。

POST`https://api.ailoot.ai/v1/images/generations`

影像

```bash
curl https://api.ailoot.ai/v1/images/generations \
  -H "Authorization: Bearer $AILOOT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2.5",
    "prompt": "水彩畫：岩石上的燈塔，黎明",
    "size": "1024x1024"
  }' 
```

```python
img = client.images.generate(
    model="gpt-image-2.5",
    prompt="水彩畫：岩石上的燈塔，黎明",
    size="1024x1024",
)
print(img.data[0].url or "base64:", (img.data[0].b64_json or "")[:40])
```

200 OK

```json
{
  "created": 1790812800,
  "data": [
    { "url": "https://…/content" }
  ],
  "usage": { "input_tokens": 18, "output_tokens": 1056 }
}
```

## 身分驗證

| 參數 | 類型 | 必填 | 說明 |
| --- | --- | --- | --- |
| `Authorization` | header | 必填 | 金鑰格式為`Bearer sk-…`。也可使用標頭`x-api-key`或`x-goog-api-key`。 |

## 請求本文

| 參數 | 類型 | 必填 | 說明 |
| --- | --- | --- | --- |
| `model` | string | 必填 | 影像模型：`gpt-image-2.5-sunburst`，`gemini-3.1-flash-image`，`grok-imagine-image-2.0`，`qwen-image-3.0-pro`，`image-01`，`gpt-image-2`，`gemini-3.1-flash-lite-image`，`grok-imagine-image`，`wan2.7-image`，`gpt-image-2.5-sunburst-2026-09-08`，`gemini-3-pro-image`，`grok-imagine-image-quality`另有[4](https://ailoot.ai/models/zh-hant-tw/?format=images)。 |
| `prompt` | string | 必填 | 影像描述。 |
| `n` | integer | 選填 | 生成影像的數量。每張完成的影像都會計費。 |
| `size` | string | 選填 | 尺寸，例如`1024x1024`。允許的尺寸取決於模型。 |
| `quality` | string | 選填 | 品質設定，僅限模型支援時 (例如`low`，`medium`，`high`). |
| `response_format` | string | 選填 | `url`或`b64_json` —僅限模型支援選擇格式時。 |

## 編輯

POST`https://api.ailoot.ai/v1/images/edits`

請求`multipart/form-data`：欄位`image` (單張或多張影像), `prompt`，`model`，必要時加上`mask`。

## 回應

| 參數 | 類型 | 必填 | 說明 |
| --- | --- | --- | --- |
| `data[]` | array |  | 完成的影像：連結`url`或資料`b64_json`，依模型而定。 |

生成前，Ailoot 會保留成果的完整費用。影像費用比文字高，請在餘額中保留足夠餘裕。每張影像或影像 token 的價格，請見[目錄](https://ailoot.ai/models/zh-hant-tw/?kind=image)。

## 編輯 · multipart/form-data

```bash
: "${AILOOT_IMAGE_EDIT_MODEL:?Select a model whose actual card or GET /v1/models method supports /v1/images/edits}"
curl --fail-with-body --max-time 300 \
  -D image-edit-headers.txt -o image-edit.json \
  https://api.ailoot.ai/v1/images/edits \
  -H "Authorization: Bearer $AILOOT_API_KEY" \
  -F "model=$AILOOT_IMAGE_EDIT_MODEL" \
  -F 'prompt=Keep the subject and replace the background with a sunset' \
  -F 'image=@input.png'
```

`input.png` → `image-edit.json` → `data[]` → `url | b64_json`

```python
import base64
import json
import mimetypes
import os
from pathlib import Path
import time
from urllib.parse import urljoin, urlsplit
from urllib.request import Request, urlopen

origin = "https://api.ailoot.ai"
out = Path("image-edit-results")
out.mkdir(exist_ok=True)

def save_all(data):
    rows = data.get("data", [])
    if not rows:
        raise RuntimeError("No completed image data; keep the original response")
    for index, row in enumerate(rows, 1):
        if row.get("b64_json"):
            content = base64.b64decode(row["b64_json"], validate=True)
            suffix = ".png" if content.startswith(b"\x89PNG") else ".bin"
        elif row.get("url"):
            url = row["url"]
            if urlsplit(url).scheme != "https":
                raise ValueError("Expected the exact returned HTTPS image URL")
            # Signed result URLs are downloaded without sending the API key to another host.
            with urlopen(url, timeout=300) as response:
                content = response.read()
                suffix = mimetypes.guess_extension(response.headers.get_content_type()) or ".bin"
        else:
            raise RuntimeError("Image has neither url nor b64_json")
        (out / ("image-%03d" % index + suffix)).write_bytes(content)


with open("image-edit.json", encoding="utf-8") as response:
    save_all(json.load(response))
```

## 影像 · async

OpenAI與Anthropic SDK 通常會自動重試網路錯誤與5xx 錯誤。生成內容時，請停用此行為 (`max_retries=0`)，並在再次嘗試前檢查`X-Should-Retry`。回應遺失不代表請求未執行。

```python
import base64
import json
import mimetypes
import os
from pathlib import Path
import time
from urllib.parse import urljoin, urlsplit
from urllib.request import Request, urlopen

origin = "https://api.ailoot.ai"
key = os.environ["AILOOT_API_KEY"]
out = Path("image-results")
out.mkdir(exist_ok=True)

def api(url, payload=None):
    url = urljoin(origin, url)
    if urlsplit(url).scheme != "https" or urlsplit(url).netloc != "api.ailoot.ai":
        raise ValueError("Unexpected API origin")
    request = Request(url, data=None if payload is None else json.dumps(payload).encode(),
                      headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
    with urlopen(request, timeout=300) as response:
        headers = dict(response.headers)
        data = json.load(response)
    (out / "response-headers.json").write_text(json.dumps(headers, indent=2))
    return data, headers

def save_all(data):
    rows = data.get("data", [])
    if not rows:
        raise RuntimeError("No completed image data; keep the original response")
    for index, row in enumerate(rows, 1):
        if row.get("b64_json"):
            content = base64.b64decode(row["b64_json"], validate=True)
            suffix = ".png" if content.startswith(b"\x89PNG") else ".bin"
        elif row.get("url"):
            url = row["url"]
            if urlsplit(url).scheme != "https":
                raise ValueError("Expected the exact returned HTTPS image URL")
            # Signed result URLs are downloaded without sending the API key to another host.
            with urlopen(url, timeout=300) as response:
                content = response.read()
                suffix = mimetypes.guess_extension(response.headers.get_content_type()) or ".bin"
        else:
            raise RuntimeError("Image has neither url nor b64_json")
        (out / ("image-%03d" % index + suffix)).write_bytes(content)

# One POST. If its result is unknown, preserve it and check history; do not rerun creation.
task, headers = api("/v1/images/generations/async", {
    "model": "gpt-image-2.5", "prompt": "Watercolor lighthouse at dawn", "size": "1024x1024"})
(out / "created-task.json").write_text(json.dumps(task, indent=2))
task_id = task.get("task_id") or task.get("id")
poll_url = task.get("poll_url") or headers.get("Location") or headers.get("location")
if not task_id or not poll_url:
    raise RuntimeError("Keep the create response and Request ID; do not submit again")

for poll in range(60):
    task, headers = api(poll_url)  # Read the original task with the same key.
    (out / "task-status.json").write_text(json.dumps(task, indent=2))
    if task.get("status") == "completed":
        result = task["result"]
        (out / "image-response.json").write_text(json.dumps(result, indent=2))
        save_all(result)
        break
    if task.get("status") == "failed":
        raise RuntimeError(json.dumps(task.get("error")))
    if task.get("status") != "processing" or task.get("result_pending_check"):
        raise RuntimeError("Keep the original task ID and check it later; no new POST")
    time.sleep(min(60, max(1, int(headers.get("Retry-After", headers.get("retry-after", "3"))))))
else:
    raise TimeoutError("Polling stopped; resume GET reads using created-task.json, never repeat POST")
```

還有疑問嗎？請提供 Request ID與問題描述，我們會協助釐清。[聯絡支援](mailto:support@ailoot.ai)

## Ailoot · 公司及其專案組合





Ailoot以累積的營運經驗、廣大的客戶群、穩定的服務及持續的KPI管理為基礎。





公司及其專案組合：數百萬客戶，每月銷售額達數十億。





Ailoot將這些營運經驗用於API存取，讓客戶的產品、代理、應用程式及自動化流程使用AI功能。
