Gemini 图像生成教程
使用 Google Imagen 3/4 模型通过 XiDao Api 生成高质量图像,支持超写实、多尺寸、批量生成等高级功能
什么是 Gemini 图像生成?
Google Imagen 是 Google DeepMind 开发的顶级文本到图像生成模型,以超高的画质、出色的细节表现和强大的指令遵循能力著称。
超高质量输出
精细的细节、丰富的光影效果、极少的伪影和瑕疵
多宽高比支持
支持 1:1, 3:4, 4:3, 16:9, 9:16 等多种比例
文字渲染能力
在图像中准确渲染文字内容,适合设计场景
多风格适配
照片级写实、油画、动漫、3D渲染等多种艺术风格
支持的模型
| 模型名称 | 模型 ID | 特性 | 成本 |
|---|---|---|---|
| Imagen 4 | imagen-4.0-generate-001 |
标准模型,画质优秀,性价比高,支持多图生成 | 标准 |
| Imagen 4 Ultra | imagen-4.0-ultra-generate-001 |
最强画质,特别擅长文字渲染,每次仅生成1张 | 较高 |
| Imagen 4 Fast | imagen-4.0-fast-generate-001 |
速度快成本低,适合原型设计和批量生成 | 低 |
| Imagen 3 | imagen-3.0-generate-002 |
上一代模型,成熟稳定,广泛验证 | 标准 |
日常推荐
imagen-4.0-generate-001 - 平衡质量与速度的最佳选择
追求极致
imagen-4.0-ultra-generate-001 - 需要最高画质时选择
快速迭代
imagen-4.0-fast-generate-001 - 快速原型和批量任务首选
快速开始
前置条件
获取 API Key
访问 api.xidao.online 注册账号并获取 API Key(格式:sk-xxxxxxxx)
安装 Python SDK
安装 Google GenAI SDK 和 Pillow 图像处理库
配置客户端
设置 API Key 和 Base URL 为 XiDao Api 地址
Python 示例
安装依赖
# 安装 Google GenAI SDK
pip install google-genai pillow
# 或安装 OpenAI 兼容库(推荐用于 XiDao Api)
pip install openai pillow requests
基础示例:生成单张图像
from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
import os
# 配置 XiDao Api
os.environ["GOOGLE_API_KEY"] = "sk-你的API_KEY"
# 初始化客户端(使用 OpenAI 兼容模式)
client = genai.Client(
api_key=os.environ["GOOGLE_API_KEY"],
http_options={
'base_url': 'https://api.xidao.online'
}
)
def generate_image(prompt, model='imagen-4.0-generate-001', **kwargs):
"""
使用 Gemini Imagen 生成图像
Args:
prompt: 图像描述(英文效果最佳)
model: 模型ID
**kwargs: 其他参数(number_of_images, aspect_ratio等)
Returns:
生成的图像列表
"""
print(f"正在生成图像:{prompt}")
# 配置生成参数
config = types.GenerateImagesConfig(
number_of_images=kwargs.get('number_of_images', 1),
aspect_ratio=kwargs.get('aspect_ratio', '1:1'),
person_generation=kwargs.get('person_generation', 'allow_adult'),
)
# 调用生成接口
response = client.models.generate_images(
model=model,
prompt=prompt,
config=config
)
# 处理生成的图像
images = []
for i, generated_image in enumerate(response.generated_images):
# 从 base64 解码图像
image_data = generated_image.image.image_bytes
image = Image.open(BytesIO(image_data))
# 保存图像
filename = f'gemini_output_{i+1}.png'
image.save(filename)
print(f"✅ 已保存:{filename} ({image.size[0]}x{image.size[1]})")
# 显示图像(如果在交互环境)
image.show()
images.append(image)
return images
# 使用示例
if __name__ == "__main__":
prompt = "A majestic dragon perched on a crystal mountain peak at sunset, \
fantasy art style, highly detailed, vibrant colors"
images = generate_image(
prompt=prompt,
model='imagen-4.0-generate-001',
aspect_ratio='16:9', # 宽屏比例
number_of_images=2 # 生成2张
)
使用 OpenAI SDK 调用(推荐)
from openai import OpenAI
import base64
from PIL import Image
from io import BytesIO
# 使用 OpenAI 兼容格式调用 Gemini Imagen
client = OpenAI(
api_key="sk-你的API_KEY",
base_url="https://api.xidao.online/v1"
)
def generate_with_openai(prompt):
"""通过 OpenAI 兼容接口调用"""
response = client.chat.completions.create(
model="gemini-2.5-flash",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": f"Generate an image: {prompt}"}
]
}
],
# 启用图像生成
extra_body={"modality": "image"}
)
return response
# 或者直接使用图像生成端点
def generate_image_direct(prompt):
"""
直接调用图像生成 API
注意:此方式需要 XiDao Api 支持 Gemini 原生图像生成
"""
response = client.images.generate(
model="imagen-4.0-generate-001",
prompt=prompt,
n=1,
size="1024x1024",
response_format="b64_json"
)
# 解码 Base64 图像
image_b64 = response.data[0].b64_json
image_data = base64.b64decode(image_b64)
image = Image.open(BytesIO(image_data))
image.save("gemini_direct.png")
print("✅ 图像已保存:gemini_direct.png")
return image
批量生成示例
from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
import os
client = genai.Client(api_key="sk-你的API_KEY")
def batch_generate(prompts, output_dir="./outputs"):
"""
批量生成多个图像
Args:
prompts: 提示词列表
output_dir: 输出目录
"""
# 创建输出目录
os.makedirs(output_dir, exist_ok=True)
results = []
for i, prompt in enumerate(prompts):
print(f"\n[{i+1}/{len(prompts)}] 生成中...")
try:
response = client.models.generate_images(
model='imagen-4.0-fast-generate-001', # 使用快速模型
prompt=prompt,
config=types.GenerateImagesConfig(
number_of_images=1,
aspect_ratio='1:1',
)
)
# 保存第一张图
img_data = response.generated_images[0].image.image_bytes
image = Image.open(BytesIO(img_data))
filename = f"{output_dir}/batch_{i+1:03d}.png"
image.save(filename)
results.append({
'prompt': prompt[:50] + "...",
'file': filename,
'size': image.size
})
print(f"✅ 已保存:{filename}")
except Exception as e:
print(f"❌ 错误:{e}")
results.append({'error': str(e)})
return results
# 批量提示词示例
prompts = [
"A serene Japanese garden with cherry blossoms in spring",
"Futuristic cyberpunk city street at night with neon lights",
"Majestic eagle soaring over snow-capped mountains",
"Cozy coffee shop interior with warm lighting and bookshelves",
"Abstract geometric pattern with gradient colors"
]
results = batch_generate(prompts)
print("\n=== 生成完成 ===")
for r in results:
if 'file' in r:
print(f"✓ {r['file']} ({r['size'][0]}x{r['size'][1]})")
高级功能:不同宽高比和质量级别
from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
client = genai.Client(api_key="sk-你的API_KEY")
def generate_with_options(prompt, options):
"""
高级选项生成
Args:
prompt: 提示词
options: 配置字典
"""
config = types.GenerateImagesConfig(
number_of_images=options.get('number_of_images', 1),
aspect_ratio=options.get('aspect_ratio', '1:1'),
person_generation=options.get('person_generation', 'allow_adult'),
)
response = client.models.generate_images(
model=options.get('model', 'imagen-4.0-generate-001'),
prompt=prompt,
config=config
)
return response
# 不同场景的配置示例
scenarios = {
'社交媒体竖图': {
'model': 'imagen-4.0-fast-generate-001',
'aspect_ratio': '9:16',
'number_of_images': 1
},
'横幅广告': {
'model': 'imagen-4.0-generate-001',
'aspect_ratio': '16:9',
'number_of_images': 1
},
'产品展示': {
'model': 'imagen-4.0-ultra-generate-001',
'aspect_ratio': '1:1',
'number_of_images': 1
},
'批量素材库': {
'model': 'imagen-4.0-fast-generate-001',
'aspect_ratio': '1:1',
'number_of_images': 4
}
}
prompt = "Professional product photography of a luxury watch on marble surface"
for scenario_name, opts in scenarios.items():
print(f"\n--- 场景:{scenario_name} ---")
response = generate_with_options(prompt, opts)
for i, img in enumerate(response.generated_images):
image = Image.open(BytesIO(img.image.image_bytes))
filename = f"{scenario_name}_{i+1}.png"
image.save(filename)
print(f"✅ {filename}")
Node.js 示例
安装依赖
# 安装 Google GenAI SDK
npm install @google/genai
# 或使用 OpenAI SDK
npm install openai
基础示例
const { GoogleGenAI } = require('@google/genai');
const fs = require('fs');
// 初始化客户端
const ai = new GoogleGenAI({
apiKey: 'sk-你的API_KEY'
});
async function generateImage(prompt, options = {}) {
const {
model = 'imagen-4.0-generate-001',
numberOfImages = 1,
aspectRatio = '1:1',
personGeneration = 'allow_adult'
} = options;
console.log(`正在生成图像:${prompt}`);
try {
const response = await ai.models.generateImages({
model: model,
prompt: prompt,
config: {
numberOfImages: numberOfImages,
aspectRatio: aspectRatio,
personGeneration: personGeneration
}
});
// 保存所有生成的图像
let idx = 1;
for (const generatedImage of response.generatedImages) {
const imgBytes = generatedImage.image.imageBytes;
const buffer = Buffer.from(imgBytes, 'base64');
const filename = `imagen-${idx}.png`;
fs.writeFileSync(filename, buffer);
console.log(`✅ 已保存:${filename}`);
idx++;
}
return response;
} catch (error) {
console.error('❌ 生成失败:', error.message);
throw error;
}
}
// 使用示例
async function main() {
await generateImage(
'A magical forest with bioluminescent plants and glowing mushrooms, \
fantasy illustration style',
{
model: 'imagen-4.0-generate-001',
numberOfImages: 2,
aspectRatio: '16:9'
}
);
}
main().catch(console.error);
Express 服务端集成
const express = require('express');
const { GoogleGenAI } = require('@google/genai');
const app = express();
app.use(express.json());
const ai = new GoogleGenAI({
apiKey: process.env.API_KEY || 'sk-你的API_KEY'
});
// 图像生成 API
app.post('/api/gemini-image', async (req, res) => {
try {
const {
prompt,
model = 'imagen-4.0-generate-001',
numberOfImages = 1,
aspectRatio = '1:1'
} = req.body;
if (!prompt) {
return res.status(400).json({ error: '缺少 prompt 参数' });
}
const response = await ai.models.generateImages({
model,
prompt,
config: {
numberOfImages,
aspectRatio,
personGeneration: 'allow_adult'
}
});
// 将图像转为 Base64 返回
const images = response.generatedImages.map((img, idx) => ({
index: idx + 1,
imageData: `data:image/png;base64,${img.image.imageBytes}`,
size: '1024x1024' // 实际尺寸取决于 aspectRatio
}));
res.json({
success: true,
model,
prompt,
count: images.length,
images
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// 批量生成 API
app.post('/api/gemini-batch', async (req, res) => {
try {
const { prompts, model = 'imagen-4.0-fast-generate-001' } = req.body;
if (!Array.isArray(prompts) || prompts.length === 0) {
return res.status(400).json({ error: 'prompts 必须是非空数组' });
}
// 限制批量数量
if (prompts.length > 10) {
return res.status(400).json({ error: '单次最多10个提示词' });
}
const results = [];
for (let i = 0; i < prompts.length; i++) {
const response = await ai.models.generateImages({
model,
prompt: prompts[i],
config: {
numberOfImages: 1,
aspectRatio: '1:1'
}
});
results.push({
promptIndex: i,
imageData: response.generatedImages[0].image.imageBytes
});
}
res.json({
success: true,
total: results.length,
results
});
} catch (error) {
res.status(500).json({ success: false, error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Gemini 图像服务运行在 http://localhost:${PORT}`);
});
REST API 示例
生成图像请求
curl -X POST "https://api.xidao.online/v1beta/models/imagen-4.0-generate-001:predict" \
-H "Authorization: Bearer sk-你的API_KEY" \
-H "Content-Type: application/json" \
-d '{
"instances": [
{
"prompt": "A stunning landscape photo of a lake surrounded by autumn trees, \
golden hour lighting, professional photography"
}
],
"parameters": {
"sampleCount": 2,
"aspectRatio": "16:9",
"personGeneration": "allow_adult"
}
}'
响应格式
{
"predictions": [
{
"bytesBase64Encoded": true,
"image": {
"imageBytes": "/9j/4AAQSkZJRg...(Base64编码的PNG数据)"
}
},
{
"bytesBase64Encoded": true,
"image": {
"imageBytes": "/9j/4AAQSkZJRg..."
}
}
]
}
下载保存图像
# 从响应中提取 Base64 数据并保存为文件
# 假设响应保存在 response.json 中
# 提取第一张图的 Base64 数据
IMAGE_B64=$(jq -r '.predictions[0].image.imageBytes' response.json)
# 解码并保存为 PNG 文件
echo "$IMAGE_B64" | base64 -d > gemini_output.png
echo "✅ 图像已保存为 gemini_output.png"
参数详解
| 参数名 | 类型 | 必填 | 默认值 | 可选值 | 说明 |
|---|---|---|---|---|---|
model |
string | 是 | - | - | 模型 ID(见上方模型表格) |
prompt |
string | 是 | - | ≤480 tokens | 图像描述(英文效果最佳) |
numberOfImages |
integer | 否 | 4 | 1-4 | 生成数量。Ultra 模式仅支持 1 |
aspectRatio |
string | 否 | 1:1 | 1:1, 3:4, 4:3, 9:16, 16:9 | 图像宽高比 |
personGeneration |
string | 否 | allow_adult | dont_allow / allow_adult / allow_all | 是否允许生成人物图像 |
imageSize |
string | 否 | 1K | 1K / 2K | 图像分辨率(Standard/Ultra 支持) |
quality |
string | 否 | high | low / medium / high | 图像质量等级 |
- **Prompt 语言**:目前主要支持英文提示词,中文效果可能不佳
- **人物生成限制**:
allow_all在欧盟、英国、瑞士、中东和北非地区不可用 - **SynthID 水印**:所有生成的图像都包含不可见的数字水印
- **付费功能**:图像生成是付费功能,需要有足够余额
- **返回格式**:默认返回 Base64 编码的 PNG 图像数据(非URL)
Prompt 编写指南
优质 Prompt 结构
一个好的 Prompt 应包含以下三个核心要素:
主体 (Subject)
明确的主要对象:人物、动物、物体或场景
示例:A majestic lion, A futuristic car, A cozy cabin
背景与环境 (Background)
主体所处的环境和背景
示例:In a misty forest, On a city rooftop at night, Against a white background
风格与细节 (Style)
艺术风格、光线、色彩、质量要求
示例:Oil painting style, Cinematic lighting, Vibrant colors, Highly detailed
实战 Prompt 示例
| 场景 | ❌ 一般写法 | ✅ 推荐写法 |
|---|---|---|
| 摄影写真 | "一只猫" | "A fluffy orange tabby cat sitting on a windowsill, \ morning sunlight streaming through the window, \ bokeh background with garden view, shot on Canon EOS R5, \ 85mm lens, f/1.8, photorealistic, highly detailed fur texture" |
| 艺术创作 | "风景画" | "An oil painting of a serene mountain lake at golden hour, \ impressionist style reminiscent of Monet, thick visible brushstrokes, \ vibrant oranges and purples reflecting on water surface, \ canvas texture visible, gallery-quality artwork" |
| 产品设计 | "一个瓶子" | "Product photography of a minimalist glass perfume bottle, \ clean white background with soft shadows, studio lighting setup, \ premium cosmetic packaging design, 8k resolution, commercial photography style" |
| 概念设计 | "未来城市" | "Futuristic cyberpunk cityscape at night, towering skyscrapers \ with holographic advertisements, flying vehicles between buildings, \ neon lights reflecting off rain-slicked streets, blade runner aesthetic, \ cinematic composition, ultra-detailed concept art" |
编写技巧
具体而非笼统
避免"A beautiful scene",改为"A serene Japanese garden with cherry blossoms in full bloom"
指定光照条件
添加:golden hour lighting, soft diffused light, dramatic side lighting, cinematic rim light 等
模拟相机参数
添加:shot on Sony A7R IV, 35mm f/1.4, shallow depth of field, 8k resolution 等
使用负面提示词思路
虽然 Imagen 不直接支持负面提示词,但可以通过正面描述间接实现,如"clean background"代替"no clutter"
使用技巧与最佳实践
成本优化策略
- 原型阶段使用 Fast 模型节省70%成本
- 批量生成时选择合适的
numberOfImages - 非必要不使用 Ultra 和 2K 分辨率
- 优化 Prompt 减少重试次数
速度优化建议
- Fast 模型响应时间约 3-5 秒
- 标准模型约 10-15 秒
- Ultra 模型约 20-30 秒
- 生产环境建议添加超时和重试机制
应用场景推荐
- 营销视觉:使用 Standard + 16:9 生成横幅素材
- 社交媒体:Fast + 9:16 快速产出竖版内容
- 电商产品:Ultra + 1:1 高质量白底图
- 游戏原画:Standard + 丰富 Prompt 细节