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

# GPT-Image-1 图像生成 API（历史文档）

> GPT-Image-1 图像生成的历史文档：gpt-image-1 系列仍可按 token 计费调用，新集成建议改用 GPT Image 2.5。

<Warning>
  **GPT-Image-1 系列是 GPT Image 的历史版本，新集成请使用 [GPT Image 2.5](/api-capabilities/gpt-image-2-5)，已有集成请尽早迁移。**

  * `gpt-image-1`、`gpt-image-1.5`、`gpt-image-1-mini` 仍在 2026 年 9 月 24 日的公开价格配置中，可以继续调用。
  * OpenAI 计划于 2026 年 10 月 23 日从 API 移除 `gpt-image-1`。
  * OpenAI 计划于 12 月 1 日移除 `gpt-image-1.5` 和 `gpt-image-1-mini`（见 [OpenAI 弃用页](https://developers.openai.com/api/docs/deprecations)）。
  * 老张API会同步停止对应模型。
</Warning>

## 模型简介

`gpt-image-1` 是 OpenAI 较早推出的 GPT Image 图像生成模型，同系列还有 `gpt-image-1.5` 和 `gpt-image-1-mini`。在老张API上按 OpenAI Images API 格式调用，生成图片的接口是 `POST https://api.laozhang.ai/v1/images/generations`，按 token 计费。

## 概述

GPT-Image-1 根据文本提示词生成图像，请求和响应沿用 OpenAI 官方 Images API 的格式。

### 主要特性

* **高质量图像生成**：生成细节丰富、符合提示词的图像
* **按 token 计费**：单价见下文「价格与分组」
* **OpenAI Images API 格式**：使用 OpenAI 官方 SDK 时，把 Base URL 设为 `https://api.laozhang.ai/v1`

## 价格与分组

2026 年 9 月 24 日公开价格配置（美元 / 每 1M tokens）：

| 模型 ID | 文本输入 | 缓存文本输入 | 输出 |
| - | -: | -: | -: |
| `gpt-image-1` | \$5 | \$1.25 | \$40 |
| `gpt-image-1.5` | \$5 | \$1.25 | \$32 |
| `gpt-image-1-mini` | \$2 | \$0.2 | \$8 |

三个模型都可以在以下分组调用，令牌的计费模式选择按量优先（推荐）或按量计费：

| 分组 | 计费 |
| - | - |
| `default` | 按上表计费，与 OpenAI 官方价格相同 |
| `Sora2Official` | 按上表计费，与 OpenAI 官方价格相同 |
| `GPTImage2 Sora2 Enterprise` | 官方价格加 20%（分组倍率 1.2） |

编辑请求上传的图片按图像输入 token 计费，各计费项的官方单价见 [OpenAI 价格页](https://developers.openai.com/api/docs/pricing)。当前价格以[模型与价格总表](/models)为准，每次请求的实际扣费见[调用日志](https://api.laozhang.ai/log)。

## 快速开始

本页示例为旧版写法：

* 除「错误处理示例」外，Python 示例使用 `openai` 0.x SDK 的 `openai.api_base` 和 `openai.Image.create`。
* Python 和 Node.js 示例都按 `url` 读取结果。返回 `b64_json` 时，按下文「响应格式」的说明保存。

### 基础配置

```python theme={null}
import openai

# 配置 老张API 的接入点和密钥
openai.api_base = "https://api.laozhang.ai/v1"
openai.api_key = "your-api-key"
```

### 生成图像

使用标准的 OpenAI Image API 格式调用：

```python theme={null}
# 生成图像
response = openai.Image.create(
    model="gpt-image-1",
    prompt="A serene landscape with mountains and a lake at sunset",
    n=1,
    size="1024x1024"
)

# 获取生成的图像 URL
image_url = response['data'][0]['url']
print(f"Generated image URL: {image_url}")
```

## API 参数详解

### 请求参数

| 参数 | 类型 | 必填 | 说明 |
| - | - | - | - |
| `model` | string | 是 | 模型 ID：`gpt-image-1`、`gpt-image-1.5` 或 `gpt-image-1-mini` |
| `prompt` | string | 是 | 图像生成的文本提示词，最长 32000 字符 |
| `n` | integer | 否 | 生成图像的数量，默认为 1，最大为 10 |
| `size` | string | 否 | 图像尺寸，支持 `1024x1024`、`1536x1024`、`1024x1536`、`auto`（默认） |
| `quality` | string | 否 | 渲染质量，支持 `low`、`medium`、`high`、`auto`（默认） |
| `output_format` | string | 否 | 输出格式，支持 `png`（默认）、`jpeg`、`webp` |
| `output_compression` | integer | 否 | 压缩级别 (0-100%)，仅适用于 JPEG 和 WebP 格式 |
| `background` | string | 否 | 背景设置，支持 `transparent`、`opaque`、`auto`（默认） |
| `response_format` | string | 否 | GPT Image 模型不支持该参数，官方接口始终返回 Base64 图片（`b64_json`） |
| `user` | string | 否 | 用户标识符，用于监控和检测滥用 |

### 参数详细说明

#### 尺寸选项 (size)

* `1024x1024` - 正方形（默认最快生成）
* `1536x1024` - 横向/风景模式
* `1024x1536` - 纵向/肖像模式
* `auto` - 模型根据提示词自动选择最佳尺寸（默认）

#### 质量选项 (quality)

* `low` - 低质量，生成速度最快
* `medium` - 中等质量
* `high` - 高质量，细节最丰富
* `auto` - 模型根据提示词自动选择（默认）

<Tip>
  **性能提示**：正方形图像 + 标准质量生成速度最快。如果对延迟敏感，建议使用 `jpeg` 格式而非 `png`。
</Tip>

#### 输出格式 (output\_format)

* `png` - 无损压缩，默认格式
* `jpeg` - 有损压缩，支持压缩级别，生成速度更快
* `webp` - 现代格式，文件更小，支持压缩级别

使用 `jpeg` 或 `webp` 时，可通过 `output_compression` 参数控制压缩级别（0-100%）。例如，`output_compression=50` 将压缩图像 50%。

#### 背景选项 (background)

* `transparent` - 透明背景（适用于 PNG/WebP）
* `opaque` - 不透明背景
* `auto` - 模型自动选择（默认）

### 响应格式

```json theme={null}
{
  "created": 1702486395,
  "data": [
    {
      "b64_json": "iVBORw0KGgo..."
    }
  ]
}
```

OpenAI 官方接口对 GPT Image 模型只返回 Base64 编码的图片（`b64_json`），不返回 `url`。

通过老张API调用时，`data[]` 中每一项可能是 `b64_json` 或 `url`，保存时两种情况都要处理，兼容两种格式的保存代码见 [GPT Image 2.5 文档](/api-capabilities/gpt-image-2-5)中的「保存图片与查看结果」。

## 使用示例

### Python 示例

```python theme={null}
import openai
import requests
from PIL import Image
from io import BytesIO

# 配置
openai.api_base = "https://api.laozhang.ai/v1"
openai.api_key = "your-api-key"

# 生成图像（使用新参数）
def generate_image(prompt, size="auto", quality="auto", output_format="png", n=1):
    try:
        response = openai.Image.create(
            model="gpt-image-1",
            prompt=prompt,
            n=n,
            size=size,
            quality=quality,
            output_format=output_format
        )
        
        # 返回图像 URLs
        return [item['url'] for item in response['data']]
    
    except Exception as e:
        print(f"Error generating image: {e}")
        return None

# 高级示例：使用压缩和背景设置
def generate_advanced_image(prompt, compression=None):
    params = {
        "model": "gpt-image-1",
        "prompt": prompt,
        "size": "1536x1024",  # 横向图片
        "quality": "high",
        "output_format": "jpeg" if compression else "png",
        "background": "transparent"
    }
    
    # 如果需要压缩，添加压缩参数
    if compression:
        params["output_compression"] = compression
    
    try:
        response = openai.Image.create(**params)
        return response['data'][0]['url']
    except Exception as e:
        print(f"Error: {e}")
        return None

# 下载并保存图像
def save_image(url, filename):
    response = requests.get(url)
    img = Image.open(BytesIO(response.content))
    img.save(filename)
    print(f"Image saved as {filename}")

# 使用示例
prompts = [
    "A futuristic city with flying cars and neon lights",
    "A cozy coffee shop in autumn with warm lighting",
    "An abstract art piece with vibrant colors and geometric shapes"
]

for i, prompt in enumerate(prompts):
    print(f"Generating: {prompt}")
    urls = generate_image(prompt)
    if urls:
        save_image(urls[0], f"image_{i+1}.png")
```

### Node.js 示例

```javascript theme={null}
const OpenAI = require('openai');
const fs = require('fs');
const https = require('https');

// 初始化客户端
const openai = new OpenAI({
  apiKey: 'your-api-key',
  baseURL: 'https://api.laozhang.ai/v1'
});

// 生成图像（使用新参数）
async function generateImage(prompt, options = {}) {
  try {
    const response = await openai.images.generate({
      model: "gpt-image-1",
      prompt: prompt,
      n: options.n || 1,
      size: options.size || "auto",
      quality: options.quality || "auto",
      output_format: options.format || "png",
      background: options.background || "auto",
      ...options.compression && { output_compression: options.compression }
    });
    
    return response.data[0].url;
  } catch (error) {
    console.error('Error generating image:', error);
    return null;
  }
}

// 高级示例：生成高质量横向图片
async function generateLandscapeImage(prompt) {
  const options = {
    size: "1536x1024",
    quality: "high",
    format: "jpeg",
    compression: 85  // 85% 质量
  };
  
  return await generateImage(prompt, options);
}

// 下载图像
function downloadImage(url, filepath) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filepath);
    https.get(url, (response) => {
      response.pipe(file);
      file.on('finish', () => {
        file.close();
        console.log(`Image saved to ${filepath}`);
        resolve();
      });
    }).on('error', reject);
  });
}

// 使用示例
async function main() {
  const prompt = "A beautiful Japanese garden with cherry blossoms";
  const imageUrl = await generateImage(prompt);
  
  if (imageUrl) {
    await downloadImage(imageUrl, 'japanese_garden.png');
  }
}

main();
```

### cURL 示例

```bash theme={null}
curl https://api.laozhang.ai/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "model": "gpt-image-1",
    "prompt": "A white siamese cat sitting on a windowsill",
    "n": 1,
    "size": "1024x1024"
  }'
```

## 提示词优化建议

### 1. 详细描述

提供具体、详细的描述以获得更好的结果：

```python theme={null}
# 基础提示词
prompt_basic = "a cat"

# 优化后的提示词
prompt_detailed = "a fluffy white Persian cat sitting on a vintage velvet cushion, soft natural lighting, professional photography, shallow depth of field"
```

### 2. 风格指定

明确指定想要的艺术风格：

```python theme={null}
styles = [
    "in the style of Studio Ghibli anime",
    "photorealistic, professional photography",
    "digital art, concept art style",
    "oil painting, impressionist style",
    "minimalist, flat design illustration"
]
```

### 3. 构图和视角

指定构图和视角可以获得更精确的结果：

```python theme={null}
compositions = [
    "close-up portrait, centered composition",
    "wide angle landscape shot, rule of thirds",
    "aerial view, bird's eye perspective",
    "low angle shot, dramatic perspective"
]
```

## 批量生成

批量生成多张图像的示例：

```python theme={null}
import asyncio
import aiohttp
import openai

async def generate_batch_images(prompts, size="1024x1024"):
    """批量生成图像"""
    tasks = []
    
    async with aiohttp.ClientSession() as session:
        for prompt in prompts:
            task = generate_single_image(session, prompt, size)
            tasks.append(task)
        
        results = await asyncio.gather(*tasks)
    
    return results

async def generate_single_image(session, prompt, size):
    """异步生成单张图像"""
    headers = {
        "Authorization": f"Bearer {openai.api_key}",
        "Content-Type": "application/json"
    }
    
    data = {
        "model": "gpt-image-1",
        "prompt": prompt,
        "n": 1,
        "size": size
    }
    
    async with session.post(
        f"{openai.api_base}/images/generations",
        headers=headers,
        json=data
    ) as response:
        result = await response.json()
        return {
            "prompt": prompt,
            "url": result['data'][0]['url']
        }

# 使用示例
prompts = [
    "A majestic eagle soaring over mountains",
    "A underwater coral reef teeming with colorful fish",
    "A cozy cabin in a snowy forest at night",
    "A bustling Tokyo street with neon signs"
]

# 运行批量生成
results = asyncio.run(generate_batch_images(prompts))
for result in results:
    print(f"Prompt: {result['prompt']}")
    print(f"URL: {result['url']}\n")
```

## 错误处理

### 常见错误码

| 错误码 | 说明 | 解决方案 |
| - | - | - |
| 400 | 无效的请求参数 | 检查提示词长度和参数格式 |
| 401 | 认证失败 | 验证 API 密钥是否正确 |
| 429 | 请求过于频繁 | 降低请求频率后重试 |
| 500 | 服务器错误 | 稍后重试或联系技术支持 |

### 错误处理示例

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

client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.laozhang.ai/v1"
)

def generate_with_retry(prompt, max_retries=3):
    """带重试机制的图像生成"""
    for attempt in range(max_retries):
        try:
            response = client.images.generate(
                model="gpt-image-1",
                prompt=prompt,
                n=1,
                size="1024x1024"
            )
            return response.data[0].url
        
        except Exception as e:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # 指数退避
                print(f"Error: {e}. Retrying in {wait_time} seconds...")
                time.sleep(wait_time)
            else:
                print(f"Failed after {max_retries} attempts: {e}")
                return None
```

## 最佳实践

### 1. 提示词长度控制

提示词最长可达 32000 字符，但通常 100-200 字符的详细描述就能获得很好的效果。

### 2. 图像尺寸和质量选择

**尺寸建议**：

* `1024x1024`：通用场景，生成速度最快
* `1536x1024`：横向构图，适合风景、横幅
* `1024x1536`：纵向构图，适合人像、海报
* `auto`：让模型根据内容自动选择

**质量建议**：

* `low`：快速预览、批量生成
* `medium`：日常使用
* `high`：专业用途、打印输出
* `auto`：模型自动优化

**格式选择**：

* `png`：需要透明背景或无损质量
* `jpeg`：追求速度和更小文件
* `webp`：现代 Web 应用，最佳压缩比

### 3. 内容审核

生成的图像会自动进行内容审核，确保符合使用政策。避免请求生成以下内容：

* 暴力或令人不安的图像
* 成人内容
* 仇恨或歧视性内容
* 误导性或虚假信息
* 侵犯版权的内容

### 4. 成本优化

* 使用较小的尺寸进行测试和预览
* 批量生成时合理设置并发数量
* 缓存生成的图像 URL，避免重复生成

## 与 Sora Image 的区别

Sora Image 已不在公开模型目录中，旧接入方式见 [Sora Image 图像生成（历史文档）](/api-capabilities/sora-image-generation)。

| 特性 | GPT-Image-1 系列 | Sora Image |
| - | - | - |
| 计费方式 | 按 token 计费，见上文「价格与分组」 | 按次计费 |
| API 类型 | Images API（`/v1/images/generations`） | Chat Completions API（`/v1/chat/completions`） |
| 尺寸支持 | `1024x1024`、`1536x1024`、`1024x1536`、`auto` | 2:3、3:2、1:1 比例 |
| 响应格式 | `data[]` 中的 `b64_json` 或 `url` | Markdown 格式图片链接 |

## 常见问题

### Q: 生成的图像可以商用吗？

A: 生成内容的使用需遵守 OpenAI 的使用政策和老张API[用户协议](https://www.laozhang.ai/zh-cn/terms)。

### Q: 图像 URL 的有效期是多久？

A: 返回 `url` 时，链接会过期，收到响应后尽快下载保存；返回 `b64_json` 时，解码后直接保存为图片文件。

### Q: 支持中文提示词吗？

A: 支持，但建议使用英文提示词以获得最佳效果。

### Q: 如何提高生成图像的质量？

A: 使用详细、具体的描述，包括风格、光线、构图等细节。

## 相关资源

* [GPT Image 2.5 API](/api-capabilities/gpt-image-2-5)：新集成使用的图像生成与编辑模型
* [GPT Image 2 API](/api-capabilities/gpt-image-2)：令牌分组、计费、生成与编辑
* [图像 API 选型](/api-capabilities/image-generation-guide)：对比当前在售的图像模型
* [GPT-Image-1 图像编辑（历史文档）](/api-capabilities/image-edit)
* [模型与价格总表](/models)
* [OpenAI 图像生成指南](https://developers.openai.com/api/docs/guides/image-generation)
* [老张API控制台](https://api.laozhang.ai)
* [技术支持](mailto:hi@laozhang.ai)


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