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

# Python 图像生成

> Python 使用 DALL-E 和 GPT-Image-2 生成和编辑图像

> 更新日期：2026-06-06

## DALL-E 3 生成图像

```python theme={null}
from openai import OpenAI

client = OpenAI(api_key="sk-xxx", base_url="https://api.crazyrouter.com/v1")

response = client.images.generate(
    model="dall-e-3",
    prompt="一只穿着宇航服的猫在月球上散步，数字艺术风格",
    size="1024x1024",
    quality="hd",
    n=1
)

image_url = response.data[0].url
print(f"图片地址: {image_url}")
```

### DALL-E 参数

| 参数        | 可选值                                   | 说明   |
| --------- | ------------------------------------- | ---- |
| `size`    | `1024x1024`, `1792x1024`, `1024x1792` | 图片尺寸 |
| `quality` | `standard`, `hd`                      | 图片质量 |
| `style`   | `vivid`, `natural`                    | 风格   |

## GPT-Image-2 生成图像

```python theme={null}
response = client.images.generate(
    model="gpt-image-2",
    prompt="一个现代简约风格的 Logo，主题是人工智能",
    size="1024x1024",
    quality="low",
    output_format="png",
    n=1
)

print(response.data[0].url)
```

## GPT-Image-2 编辑图像

```python theme={null}
# 图像编辑（需要原图）
response = client.images.edit(
    model="gpt-image-2",
    image=open("original.png", "rb"),
    prompt="把背景改成海滩日落",
    size="1024x1024",
    quality="low"
)

print(response.data[0].url)
```

## 下载并保存图片

```python theme={null}
import requests

response = client.images.generate(
    model="dall-e-3",
    prompt="赛博朋克风格的城市夜景",
    size="1792x1024"
)

# 下载图片
image_url = response.data[0].url
img_data = requests.get(image_url).content
with open("cyberpunk_city.png", "wb") as f:
    f.write(img_data)
print("图片已保存")
```

<Note>
  `gpt-image-2` 通常返回 `data[0].url`。不要给 `gpt-image-2` 传 `response_format`；如需控制图片文件格式，请使用 `output_format="png"`、`"jpeg"` 或 `"webp"`。生产图片请求建议使用主承接线路 `https://api.crazyrouter.com/v1`。
</Note>

<Warning>
  图像生成费用较高，建议先用小尺寸测试 prompt 效果，满意后再生成高质量大图。
</Warning>
