关于 gemini-3-image-generation
面向使用 Gemini 3 Pro Image 的开发者,提供图像生成技能指南,涵盖提示词生成、4K 输出、图中文字、搜索依据生成及多轮编辑。
主要功能
- 01文本生成图像
- 02原生 4K 与升频
- 03图像内文字渲染
- 04Google Search 依据生成
- 05多轮对话式编辑
- 06自定义宽高比
适用场景
- 01从提示词生成图像
- 02制作高分辨率视觉素材
- 03生成含可读文字的设计稿
- 04迭代修改图像
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ adaptationio/ skrillz --skill gemini-3-image-generation安装后在 Claude Code 中输入/gemini-3-image-generation确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/conversational-editing.mdgeneration-guide.mdgrounded-generation.mdmodel-setup.mdpricing-optimization.mdresolution-guide.mdscripts/edit-image.pygenerate-image.pygrounded-gen.py详细介绍
Gemini 3 Pro 图像生成(Nano Banana Pro)
使用 Gemini 3 Pro Image(gemini-3-pro-image-preview)生成图像的全面指南,该模型也称为 Nano Banana Pro。本技能专注于图像输出(生成图像)——如需输入(分析图像),请参阅 gemini-3-multimodal。
概述
Gemini 3 Pro Image(Nano Banana Pro 🍌)是 Google 的图像生成模型,支持原生 4K、图像内文本渲染、借助 Google Search 实现有依据的生成,以及对话式编辑功能。
主要功能
- **4K 分辨率:**原生 4K 生成,支持升频至 2K/4K
- **文本渲染:**在图像中渲染高质量文本
- **有依据的生成:**使用 Google Search 生成经事实核验的图像
- **对话式编辑:**通过多轮对话修改图像并保留上下文
- **宽高比:**支持 4K 下的 16:9 和自定义比例
- **质量控制:**经过微调的生成参数
何时使用此技能
- 根据文本提示生成图像
- 创建 4K 分辨率图像
- 在图像中渲染文本
- 生成经事实核验的图像(有依据的生成)
- 对话式图像编辑
- 多轮图像优化
- 自定义宽高比图像
快速入门
前提条件
- Gemini API 设置(请参阅
gemini-3-pro-api技能) - 模型:
gemini-3-pro-image-preview
Python 快速入门
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY")
# Use the image generation model
model = genai.GenerativeModel("gemini-3-pro-image-preview")
# Generate image
response = model.generate_content("A serene mountain landscape at sunset")
# Save image
if response.parts:
with open("generated_image.png", "wb") as f:
f.write(response.parts[0].inline_data.data)
print("Image saved!")
Node.js 快速入门
import { GoogleGenerativeAI } from "@google/generative-ai";
import fs from "fs";
const genAI = new GoogleGenerativeAI("YOUR_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-3-pro-image-preview" });
const result = await model.generateContent("A serene mountain landscape at sunset");
const imageData = result.response.parts[0].inlineData.data;
fs.writeFileSync("generated_image.png", Buffer.from(imageData, "base64"));
console.log("Image saved!");
核心任务
任务 1:根据文本提示生成图像
**目标:**根据文本描述创建高质量图像。
Python 示例:
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel(
"gemini-3-pro-image-preview",
generation_config={
"thinking_level": "high", # Best quality
"temperature": 1.0
}
)
# Generate image
prompt = """A futuristic cityscape at night with:
- Neon lights and holographic advertisements
- Flying vehicles
- Tall skyscrapers with unique architecture
- Rain-slicked streets reflecting the lights
- Cinematic, detailed, 4K quality"""
response = model.generate_content(prompt)
# Save image
if response.parts and hasattr(response.parts[0], 'inline_data'):
image_data = response.parts[0].inline_data.data
with open("futuristic_city.png", "wb") as f:
f.write(image_data)
print("Image generated successfully!")
else:
print("No image generated")
改进提示词的技巧:
- 描述具体、详尽
- 指定艺术风格(写实、卡通、油画等)
- 包含光线、情绪和氛围
- 提及质量等级(4K、细节丰富、高质量)
- 描述颜色、纹理和构图
参阅:references/generation-guide.md,了解全面的提示词编写技巧
任务 2:生成 4K 图像
**目标:**通过升频创建高分辨率 4K 图像。
Python 示例:
# Generate with 4K quality specification
prompt = """A photorealistic portrait of a scientist in a modern lab:
- 4K ultra-high definition
- Sharp focus on subject
- Soft bokeh background
- Professional studio lighting
- Fine detail in textures
- Cinema-grade quality"""
response = model.generate_content(prompt)
# 4K image will be generated
if response.parts:
with open("scientist_4k.png", "wb") as f:
f.write(response.parts[0].inline_data.data)
4K 功能:
- 支持原生 4K 分辨率
- 升频至 2K/4K
- 支持 4K 下的 16:9 宽高比
- 提升细节和清晰度
参阅:references/resolution-guide.md,了解分辨率控制
任务 3:在图像中渲染文本
**目标:**生成包含清晰易读、高质量文本的图像。
Python 示例:
prompt = """Create a professional business card design with:
- Company name: "TechVision AI"
- Text: "Dr. Sarah Chen"
- Text: "Chief AI Officer"
- Text: "[email protected]"
- Text: "+1 (555) 123-4567"
- Modern, clean design
- Professional fonts
- Blue and white color scheme
- All text clearly readable"""
response = model.generate_content(prompt)
if response.parts:
with open("business_card.png", "wb") as f:
f.write(response.parts[0].inline_data.data)
文本渲染最佳实践:
- 在引号中明确指定文本内容
- 要求文本“清晰易读”或“清晰可见”
- 保持文本简短、简单
- 可按需指定字体样式
- 使用高对比度背景
参阅:references/generation-guide.md,了解文本渲染技巧
任务 4:有依据的生成(经事实核验的图像)
**目标:**使用 Google Search grounding 生成功能准确的图像。
Python 示例:
# Enable Google Search grounding for factual accuracy
model_grounded = genai.GenerativeModel(
"gemini-3-pro-image-preview",
tools=[{"google_search_retrieval": {}}] # Enable grounding
)
prompt = """Generate an accurate image of the International Space Station
with Earth in the background. Use current ISS configuration."""
response = model_grounded.generate_content(prompt)
if response.parts:
with open("iss_grounded.png", "wb") as f:
f.write(response.parts[0].inline_data.data)
# Check if grounding was used
if hasattr(response, 'grounding_metadata'):
print(f"Grounding sources used: {len(response.grounding_metadata.grounding_chunks)}")
有依据的生成适用场景:
- 历史场景(符合相应时代)
- 科学可视化
- 时事
- 著名地标
- 产品展示图
优势:
- 确保事实准确
- 以现实世界信息为依据
- 减少幻觉
- 信息保持最新
**注意:**使用免费的 Google Search 配额(每天 1,500 次查询)
参阅:references/grounded-generation.md,了解全面指南
任务 5:对话式图像编辑
**目标:**通过多轮对话逐步优化图像。
Python 示例:
model = genai.GenerativeModel("gemini-3-pro-image-preview")
# Start a chat session for conversational editing
chat = model.start_chat()
# First generation
response1 = chat.send_message("Create a cozy coffee shop interior")
if response1.parts:
with open("coffee_shop_v1.png", "wb") as f:
f.write(response1.parts[0].inline_data.data)
# Refine the image
response2 = chat.send_message("Add more plants and warm lighting")
if response2.parts:
with open("coffee_shop_v2.png", "wb") as f:
f.write(response2.parts[0].inline_data.data)
# Further refinement
response3 = chat.send_message("Make it more minimalist, remove some decorations")
if response3.parts:
with open("coffee_shop_v3.png", "wb") as f:
f.write(response3.parts[0].inline_data.data)
对话式编辑功能:
- 在多轮对话中保留视觉上下文
- 逐步修改
- 使用自然语言指令
- 多轮优化
- 根据上下文进行更改
编辑指令示例:
- “调暗/调亮一些”
- “添加更多[元素]”
- “将配色方案改为[颜色]”
- “让它更写实/更具艺术感”
- “移除[元素]”
参阅:references/conversational-editing.md,了解高级模式
任务 6:自定义宽高比
目标: 按指定宽高比生成图像。
Python 示例:
# 16:9 aspect ratio (4K supported)
prompt_169 = "A cinematic landscape in 16:9 aspect ratio, 4K quality"
# Square aspect ratio
prompt_square = "A square logo design for a tech company"
# Portrait orientation
prompt_portrait = "A portrait-oriented movie poster"
response = model.generate_content(prompt_169)
# Image will be generated in specified ratio
支持的宽高比:
- 16:9 - 宽屏、电影效果(支持 4K)
- 1:1 - 正方形
- 4:3 - 标准
- 9:16 - 竖屏/肖像
任务 7:优化图像生成成本
目标: 平衡图像生成的质量和成本。
定价:
- 文本输入: 每 1M 个 token 收费 $1-2
- 文本输出: 每 1M 个 token 收费 $6-9
- 图像输出: 每张图像收费 $0.134(价格因分辨率而异)
Python 成本优化:
def generate_with_cost_tracking(prompt):
"""Generate image and track costs"""
response = model.generate_content(prompt)
# Calculate cost
usage = response.usage_metadata
input_cost = (usage.prompt_token_count / 1_000_000) * 2.00
output_cost = (usage.candidates_token_count / 1_000_000) * 9.00
image_cost = 0.134 # Per image
total_cost = input_cost + output_cost + image_cost
print(f"Input tokens: {usage.prompt_token_count} (${input_cost:.6f})")
print(f"Output tokens: {usage.candidates_token_count} (${output_cost:.6f})")
print(f"Image cost: ${image_cost:.6f}")
print(f"Total: ${total_cost:.6f}")
return response
response = generate_with_cost_tracking("A beautiful sunset over mountains")
成本优化策略:
- 批量请求: 在一个会话中生成多张图像
- 重复使用聊天会话: 对话式编辑效率更高
- 使用具体的提示词: 清晰的提示词可减少重新生成的需求
- 监控用量: 跟踪每个项目的成本
- 选择合适的质量: 并非所有图像都需要 4K
参见: references/pricing-optimization.md,了解详细策略
批量图像生成
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel("gemini-3-pro-image-preview")
prompts = [
"A serene mountain lake at dawn",
"A bustling market in Morocco",
"A futuristic robot assistant",
"An abstract geometric pattern"
]
for i, prompt in enumerate(prompts):
print(f"Generating image {i+1}/{len(prompts)}: {prompt}")
response = model.generate_content(prompt)
if response.parts:
with open(f"generated_{i+1}.png", "wb") as f:
f.write(response.parts[0].inline_data.data)
print(f" Saved: generated_{i+1}.png")
错误处理
from google.api_core import exceptions
def safe_image_generation(prompt):
"""Generate image with error handling"""
try:
response = model.generate_content(prompt)
if not response.parts:
return {"success": False, "error": "No image generated"}
if not hasattr(response.parts[0], 'inline_data'):
return {"success": False, "error": "Invalid response format"}
return {
"success": True,
"image_data": response.parts[0].inline_data.data,
"mime_type": response.parts[0].inline_data.mime_type
}
except exceptions.InvalidArgument as e:
return {"success": False, "error": f"Invalid prompt: {e}"}
except exceptions.ResourceExhausted as e:
return {"success": False, "error": f"Rate limit exceeded: {e}"}
except Exception as e:
return {"success": False, "error": f"Error: {e}"}
参考资料
核心指南
优化
脚本
官方资源
相关技能
- gemini-3-pro-api - 基础设置、身份验证、文本生成
- gemini-3-multimodal - 图像输入(分析图像)
- gemini-3-advanced - 高级功能(缓存、批处理、工具)
最佳实践
- 描述具体: 详细的提示词能生成更好的结果
- 指定质量: 明确要求 4K 或高质量
- 使用事实依据: 启用此功能以提高事实准确性
- 通过对话迭代: 使用聊天进行优化
- 监控成本: 跟踪用量,尤其是 4K 图像
- 处理错误: 实现重试逻辑
- 正确保存图像: 使用二进制模式写入
故障排除
问题:未生成图像
解决方案: 检查 response.parts 是否存在,以及是否具有 inline_data 属性
问题:图像质量较低
解决方案: 在提示词中添加“4K”“高质量”“细节丰富”
问题:图像中的文字无法辨认
解决方案: 用引号明确指定文字,并要求“文字清晰可读”
问题:图像内容不符合事实
解决方案: 启用基于事实的生成,并使用 Google Search
问题:成本过高
解决方案: 优化提示词、批量发送请求并监控用量
总结
此技能提供完整的图像生成能力:
✅ 文本生成图像 ✅ 原生支持 4K ✅ 在图像中渲染文字 ✅ 基于事实的生成(经事实核验) ✅ 对话式编辑 ✅ 自定义宽高比 ✅ 成本优化 ✅ 可用于生产环境的示例
准备好生成图像了吗? 从上文的任务 1:根据文本提示词生成图像开始!