GPT 图像生成教程

使用 OpenAI DALL-E 3 / GPT-Image 模型通过 XiDao Api 生成高质量图像,支持文本转图像、图像编辑等能力

什么是 GPT 图像生成?

OpenAI 图像生成 API 提供强大的 AI 图像创建能力,支持从文本描述生成高质量图像、编辑现有图像等功能。

🎨

文本生成图像

通过自然语言描述生成高质量、高分辨率的图像,支持多种艺术风格

✏️

图像编辑

基于原图进行局部修改、风格转换、元素替换等编辑操作

🔄

图像变体

生成与原图相似但细节不同的变体版本,适合批量创作

快速响应

通过 XiDao Api 亚洲优化节点,获得更快的图像生成速度

支持的模型

模型名称模型 ID特性支持尺寸
DALL-E 3 dall-e-3 最高质量,提示词理解能力强,自动优化 prompt 1024×1024, 1792×1024, 1024×1792
DALL-E 2 dall-e-2 经典模型,速度快,成本低,支持批量生成 256×256, 512×512, 1024×1024
GPT-Image-1 gpt-image-1 新一代模型,超写实主义,支持多模态输入 1024×1024, 1024×1536, 1536×1024
GPT-Image-1.5 gpt-image-1.5 最强画质,指令遵循度高,多图生成 1024×1024, 1024×1536, 1536×1024
💡
推荐 日常使用推荐 dall-e-3,需要高质量写实图像时选择 gpt-image-1.5

快速开始

前置条件

1

获取 API Key

访问 api.xidao.online 注册账号并获取 API Key(格式:sk-xxxxxxxx)

2

安装依赖库

根据你的编程语言安装对应的 OpenAI SDK 或 HTTP 客户端库

3

配置 Base URL

将 API 基础地址设置为 https://api.xidao.online/v1

Python 示例

安装依赖

bash
pip install openai requests pillow

基础示例:文本生成图像

python
import os
import requests
from openai import OpenAI

# 初始化客户端
client = OpenAI(
    api_key="sk-你的API_KEY",
    base_url="https://api.xidao.online/v1"
)

def generate_image(prompt, size="1024x1024", quality="standard", model="dall-e-3"):
    """
    生成图像
    
    Args:
        prompt: 图像描述(建议英文效果更好)
        size: 图像尺寸
        quality: 图像质量 (standard/hd)
        model: 模型名称
    """
    print(f"正在生成图像:{prompt}...")
    
    response = client.images.generate(
        model=model,
        prompt=prompt,
        size=size,
        quality=quality,
        n=1,  # DALL-E 3 只支持 n=1
        style="vivid"  # vivid(生动) 或 natural(自然)
    )
    
    # 获取图像 URL
    image_url = response.data[0].url
    print(f"✅ 生成成功!URL: {image_url}")
    
    # 获取优化后的提示词
    revised_prompt = response.data[0].revised_prompt
    print(f"优化后的提示词:{revised_prompt}")
    
    # 下载图像到本地
    download_image(image_url, "output.png")
    
    return image_url

def download_image(url, filename):
    """下载图像到本地"""
    img_data = requests.get(url).content
    with open(filename, 'wb') as f:
        f.write(img_data)
    print(f"📷 图像已保存为:{filename}")

# 使用示例
if __name__ == "__main__":
    prompt = "A cute cat wearing an astronaut suit walking on Mars surface, \
with Earth visible in the background, photorealistic style, highly detailed"
    
    image_url = generate_image(
        prompt=prompt,
        size="1024x1024",
        quality="hd",  # 高清模式
        model="dall-e-3"
    )

批量生成示例

python
from openai import OpenAI
import requests

client = OpenAI(
    api_key="sk-你的API_KEY",
    base_url="https://api.xidao.online/v1"
)

# 批量生成多个提示词
prompts = [
    "A futuristic city skyline at sunset, cyberpunk style",
    "A peaceful Japanese garden in spring with cherry blossoms",
    "An abstract digital art piece with vibrant colors"
]

for i, prompt in enumerate(prompts):
    print(f"\n--- 生成第 {i+1} 张图像 ---")
    
    response = client.images.generate(
        model="dall-e-3",
        prompt=prompt,
        size="1024x1024",
        quality="standard",
        n=1
    )
    
    image_url = response.data[0].url
    
    # 下载并保存
    img_data = requests.get(image_url).content
    filename = f"image_{i+1}.png"
    with open(filename, 'wb') as f:
        f.write(img_data)
    
    print(f"✅ 已保存:{filename}")

图像编辑示例

python
from openai import OpenAI
import base64

client = OpenAI(
    api_key="sk-你的API_KEY",
    base_url="https://api.xidao.online/v1"
)

def edit_image(image_path, prompt, output_path):
    """
    编辑图像
    
    Args:
        image_path: 原始图像路径
        prompt: 编辑描述
        output_path: 输出路径
    """
    # 读取图像并转为 base64
    with open(image_path, "rb") as f:
        image_data = f.read()
        image_base64 = base64.b64encode(image_data).decode('utf-8')
    
    # 调用编辑接口
    response = client.images.edit(
        model="dall-e-2",  # 编辑功能目前只支持 dall-e-2
        image=image_data,
        prompt=prompt,
        size="1024x1024",
        n=1
    )
    
    # 获取结果
    edited_url = response.data[0].url
    print(f"✅ 编辑完成!URL: {edited_url}")
    
    # 下载编辑后的图像
    import requests
    img_data = requests.get(edited_url).content
    with open(output_path, 'wb') as f:
        f.write(img_data)
    print(f"📷 已保存:{output_path}")

# 使用示例:将图像中的猫换成狗
edit_image(
    image_path="original_cat.png",
    prompt="Replace the cat with a golden retriever dog",
    output_path="edited_dog.png"
)

Node.js 示例

安装依赖

bash
npm install openai fs axios

基础示例

javascript
const OpenAI = require('openai');
const fs = require('fs');
const axios = require('axios');
const path = require('path');

// 初始化客户端
const client = new OpenAI({
    apiKey: 'sk-你的API_KEY',
    baseURL: 'https://api.xidao.online/v1'
});

async function generateImage(prompt, options = {}) {
    const {
        size = '1024x1024',
        quality = 'standard',
        model = 'dall-e-3',
        style = 'vivid'
    } = options;

    console.log(`正在生成图像:${prompt}`);

    try {
        const response = await client.images.generate({
            model,
            prompt,
            size,
            quality,
            n: 1,
            style
        });

        const imageUrl = response.data[0].url;
        console.log(`✅ 生成成功!URL: ${imageUrl}`);

        // 获取优化后的提示词
        if (response.data[0].revised_prompt) {
            console.log(`优化后的提示词:${response.data[0].revised_prompt}`);
        }

        // 下载图像
        await downloadImage(imageUrl, 'output.png');

        return imageUrl;
    } catch (error) {
        console.error('❌ 生成失败:', error.message);
        throw error;
    }
}

async function downloadImage(url, filename) {
    const response = await axios({
        method: 'GET',
        url: url,
        responseType: 'arraybuffer'
    });

    fs.writeFileSync(filename, response.data);
    console.log(`📷 图像已保存为:${filename}`);
}

// 使用示例
async function main() {
    const prompt = 'A beautiful landscape painting of mountains at sunrise, \
oil painting style, vibrant colors';

    await generateImage(prompt, {
        size: '1792x1024',  // 横向宽屏
        quality: 'hd',       // 高清模式
        model: 'dall-e-3',
        style: 'natural'     // 自然风格
    });
}

main().catch(console.error);

Express 服务端集成

javascript
const express = require('express');
const OpenAI = require('openai');
const axios = require('axios');
const app = express();

app.use(express.json());

const client = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY || 'sk-你的API_KEY',
    baseURL: 'https://api.xidao.online/v1'
});

// 图像生成 API 端点
app.post('/api/generate-image', async (req, res) => {
    try {
        const { prompt, size, quality, model } = req.body;

        const response = await client.images.generate({
            model: model || 'dall-e-3',
            prompt,
            size: size || '1024x1024',
            quality: quality || 'standard',
            n: 1
        });

        const imageUrl = response.data[0].url;
        
        // 返回图像 URL 和元数据
        res.json({
            success: true,
            url: imageUrl,
            revisedPrompt: response.data[0].revised_prompt,
            model: model || 'dall-e-3'
        });

    } catch (error) {
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// 下载图像端点
app.get('/api/download-image', async (req, res) => {
    try {
        const { url } = req.query;
        const response = await axios({ url, responseType: 'stream' });
        
        res.setHeader('Content-Type', 'image/png');
        response.data.pipe(res);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});

cURL / REST API 示例

生成图像

bash
curl -X POST "https://api.xidao.online/v1/images/generations" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-你的API_KEY" \
  -d '{
    "model": "dall-e-3",
    "prompt": "A serene lake surrounded by mountains at sunset, \
photorealistic, 8k resolution",
    "n": 1,
    "size": "1024x1024",
    "quality": "hd",
    "style": "vivid"
  }'

响应示例

json
{
  "created": 1704067200,
  "data": [
    {
      "revised_prompt": "A photorealistic scene of a tranquil alpine lake \
surrounded by snow-capped mountains during golden hour sunset...",
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/..."
    }
  ]
}

编辑图像

bash
# 先将图像转为 base64
IMAGE_BASE64=$(base64 -w 0 input.png)

curl -X POST "https://api.xidao.online/v1/images/edits" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-你的API_KEY" \
  -d "{
    \"model\": \"dall-e-2\",
    \"prompt\": \"Change the background to a beach scene\",
    \"image\": \"$IMAGE_BASE64\",
    \"n\": 1,
    \"size\": \"1024x1024\"
  }"

参数详解

参数名 类型 必填 默认值 说明
model string - 模型ID:dall-e-3, dall-e-2, gpt-image-1, gpt-image-1.5
prompt string - 图像描述文本(最多4000字符,英文效果最佳)
n integer 1 生成数量。DALL-E 3 仅支持 1;DALL-E 2 支持 1-10;GPT-Image 支持 1-10
size string 1024x1024 图像尺寸。DALL-E 3: 1024², 1792×1024, 1024×1792;DALL-E 2: 256², 512², 1024²;GPT-Image: 1024², 1024×1536, 1536×1024
quality string standard 图像质量:standard(标准) 或 hd(高清,消耗更多积分)。仅 DALL-E 3 支持
style string vivid 艺术风格:vivid(生动/超现实) 或 natural(自然/写实)。仅 DALL-E 3 支持
response_format string url 返回格式:url(返回URL,1小时有效) 或 b64_json(返回Base64编码)
⚠️
重要提示
  • 图像 URL 有效期通常只有 **1小时**,请及时下载保存
  • DALL-E 3 会自动**优化你的提示词**,可通过 revised_prompt 字段查看
  • 有严格的内容安全政策,涉及暴力、色情、政治人物等会被拒绝
  • 生成时间约 **5-15秒**,生产环境建议添加超时处理

高级用法

Base64 格式返回

如果不想处理URL过期问题,可以直接返回Base64编码的图像数据:

python
response = client.images.generate(
    model="dall-e-3",
    prompt="A beautiful landscape",
    size="1024x1024",
    response_format="b64_json"  # 返回 Base64 编码
)

# 获取 Base64 数据
image_b64 = response.data[0].b64_json

# 保存为文件
import base64
with open("output.png", "wb") as f:
    f.write(base64.b64decode(image_b64))

异步批量生成

python
import asyncio
import aiohttp
from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key="sk-你的API_KEY",
    base_url="https://api.xidao.online/v1"
)

async def generate_async(prompt, index):
    """异步生成单张图像"""
    print(f"[{index}] 开始生成...")
    response = await client.images.generate(
        model="dall-e-3",
        prompt=prompt,
        size="1024x1024",
        quality="standard"
    )
    print(f"[{index}] ✅ 完成")
    return response.data[0].url

async def batch_generate(prompts):
    """批量并发生成"""
    tasks = [generate_async(p, i) for i, p in enumerate(prompts)]
    results = await asyncio.gather(*tasks)
    return results

# 使用示例
prompts = [
    "Abstract art with geometric shapes",
    "Futuristic cityscape at night",
    "Portrait of a robot artist"
]

results = asyncio.run(batch_generate(prompts))
for i, url in enumerate(results):
    print(f"图像{i+1}: {url}")

Web 应用集成示例

html
<!DOCTYPE html>
<html>
<head>
    <title>AI Image Generator</title>
</head>
<body>
    <textarea id="prompt" placeholder="输入图像描述..." rows="4" cols="50"></textarea>
    <select id="size">
        <option value="1024x1024">1024x1024</option>
        <option value="1792x1024">1792x1024 (横向)</option>
        <option value="1024x1792">1024x1792 (纵向)</option>
    </select>
    <button onclick="generate()">生成图像</button>
    <br><br>
    <img id="result" style="max-width:100%;">

    <script>
    const API_KEY = 'sk-你的API_KEY';
    const BASE_URL = 'https://api.xidao.online/v1';

    async function generate() {
        const prompt = document.getElementById('prompt').value;
        const size = document.getElementById('size').value;
        
        document.getElementById('result').src = '';
        
        const response = await fetch(`${BASE_URL}/images/generations`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`
            },
            body: JSON.stringify({
                model: 'dall-e-3',
                prompt: prompt,
                size: size,
                quality: 'hd',
                n: 1
            })
        });
        
        const data = await response.json();
        document.getElementById('result').src = data.data[0].url;
    }
    </script>
</body>
</html>

使用技巧与最佳实践

📝

编写高质量 Prompt

  • 使用英文描述效果更好
  • 包含主体、背景、风格、光线等要素
  • 指定艺术风格:photorealistic, oil painting, anime 等
  • 添加质量修饰词:highly detailed, 8k, professional

性能优化

  • 非必要不使用 HD 质量(节省50%成本)
  • 批量任务使用异步请求提高效率
  • 及时下载保存,避免URL失效
  • 考虑缓存常用 prompt 的结果
🎯

场景化应用

  • 内容创作:博客配图、社交媒体素材
  • 产品设计:原型设计、UI mockup
  • 营销物料:广告创意、海报设计
  • 游戏开发:角色概念、场景原画
XiDao Api 优势 通过 XiDao Api 使用图像生成 API,享受亚洲优化的低延迟网络、统一计费和多模型切换能力,无需分别注册各平台账号。