mcpField
N
nanobanana

nanobanana

github.com/kenneth-liao创意与媒体12741 次安装31 周前更新
代码仓库

关于 nanobanana

nanobanana 是使用 Google Gemini 模型生成和编辑图像的命令行与 Python 技能,支持文本提示词、参考图、批量生成,以及可选模型、比例和尺寸。

主要功能

  1. 01文本生成图像
  2. 02通过自然语言编辑图像
  3. 03支持最多 14 张参考图
  4. 04批量与连续生成
  5. 05可选模型、比例和尺寸
  6. 06Google Search grounding

适用场景

  1. 01用 Flash 探索图像创意
  2. 02用 Pro 制作最终图像
  3. 03通过文字指令编辑图像
  4. 04借助参考图制作风格一致的系列

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kenneth-liao/ai-launchpad-marketplace --skill nanobanana

安装后在 Claude Code 中输入/nanobanana确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

.gitignore
requirements.txt
references/
gemini-api.md
prompts.md
scripts/
batch_generate.py
generate.py

详细介绍

Nano Banana - AI 图像生成

使用 Google Gemini 模型生成和编辑图像。支持两种模型:

  • Pro(gemini-3-pro-image-preview)— 高质量,适用于复杂提示词,支持思考模式
  • Flash(gemini-2.5-flash-image)— 快速、经济,适合迭代

前提条件

必需:

  • GEMINI_API_KEY — 从 Google AI Studio 获取
  • uv(推荐),或已安装 google-genai 的 Python 3.10+

使用 uv(推荐 — 无需设置): 依赖通过 PEP 723 内联声明,并会在首次运行时自动安装。只需使用 uv run 替代 python3。

使用 pip(备用方案):

pip install -r ${CLAUDE_SKILL_DIR}/requirements.txt

快速开始

默认输出: 图像会自动保存到 ~/Downloads/nanobanana_<timestamp>.png。除非用户指定保存位置,否则不要传入 -o。如果用户提供的文件名没有目录(例如“将其保存为 robot.png”),请使用 -o ~/Downloads/robot.png。

生成图像:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py "a cute robot mascot, pixel art style"
编辑现有图像:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py "make the background blue" -i input.jpg
使用 Flash 模型快速迭代:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py "quick sketch of a cat" --model flash
多图参考(风格 + 主体):
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py "apply the style of the first image to the second" \
  -i style_ref.png subject.jpg
使用指定的宽高比和分辨率生成:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py "cinematic landscape" --ratio 21:9 --size 4K
保存到指定位置:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py "logo design" -o ~/Projects/brand/logo.png

模型选择指南

Pro(默认)Flash
速度较慢快约 2~3 倍
成本较高较低
文本渲染良好不稳定
复杂场景出色尚可
思考模式支持不支持
最适合最终成品图像探索、草稿、批量生成

经验法则: 探索和批量生成使用 Flash,最终输出使用 Pro。

脚本参考

scripts/generate.py

主要图像生成脚本。

Usage: generate.py [OPTIONS] PROMPT

Arguments:
  PROMPT                Text prompt for image generation

Options:
  -o, --output PATH     Output file path (default: ~/Downloads/nanobanana_<timestamp>.png)
  -i, --input PATH...   Input image(s) for editing / reference (up to 14)
  -m, --model MODEL     Model: 'pro' (default), 'flash', or full model ID
  -r, --ratio RATIO     Aspect ratio (1:1, 16:9, 9:16, 21:9, etc.)
  -s, --size SIZE       Image size: 1K, 2K, or 4K (default: standard)
  --search              Enable Google Search grounding for accuracy
  --retries N           Max retries on rate limit (default: 3)
  -v, --verbose         Show detailed output

支持的宽高比:

  • 1:1 — 正方形(默认)
  • 2:3、3:2 — 纵向/横向
  • 3:4、4:3 — 标准
  • 4:5、5:4 — 照片
  • 9:16、16:9 — 宽屏
  • 21:9 — 超宽屏/电影级

图像尺寸:

  • 1K — 快速,细节较少
  • 2K — 细节增强(2048px)
  • 4K — 最高质量(3840px),最适合文本渲染
scripts/batch_generate.py

使用连续命名生成多张图像。

Usage: batch_generate.py [OPTIONS] PROMPT

Arguments:
  PROMPT                Text prompt for image generation

Options:
  -n, --count N         Number of images to generate (default: 10)
  -d, --dir PATH        Output directory (default: ~/Downloads)
  -p, --prefix STR      Filename prefix (default: "image")
  -m, --model MODEL     Model: 'pro' (default), 'flash', or full model ID
  -r, --ratio RATIO     Aspect ratio
  -s, --size SIZE       Image size (1K/2K/4K)
  --search              Enable Google Search grounding
  --retries N           Max retries per image on rate limit (default: 3)
  --delay SECONDS       Delay between generations (default: 3)
  --parallel N          Concurrent requests (default: 1, max recommended: 5)
  -q, --quiet           Suppress progress output

示例:

uv run ${CLAUDE_SKILL_DIR}/scripts/batch_generate.py "pixel art logo" -n 20 --model flash -d ./logos -p logo

Python API

直接导入(从其他技能的脚本中):

注意: 作为 Python 模块导入时,调用脚本的环境中必须能够使用 google-genai。如果使用 uv run,请在自己的脚本中添加 PEP 723 dependencies 块(参见下方模式 2 中的示例)。

import sys
from pathlib import Path
sys.path.insert(0, str(Path("${CLAUDE_SKILL_DIR}/scripts")))
from generate import generate_image, edit_image, batch_generate

# Generate image
result = generate_image(
    prompt="a futuristic city at night",
    output_path="city.png",
    aspect_ratio="16:9",
    image_size="4K",
    model="pro",
)

# Edit existing image
result = edit_image(
    prompt="add flying cars to the sky",
    input_path="city.png",
    output_path="city_edited.png",
)

# Multi-image reference
result = generate_image(
    prompt="combine the color palette of the first with the composition of the second",
    input_paths=["palette_ref.png", "composition_ref.png"],
    output_path="combined.png",
)
返回结构(始终存在):
{
    "success": True,       # or False
    "path": "/path/to/output.png",  # or None on failure
    "error": None,         # or error message string
    "metadata": {
        "model": "gemini-3-pro-image-preview",
        "prompt": "...",
        "aspect_ratio": "16:9",
        "image_size": "4K",
        "use_search": False,
        "input_images": None,        # or list of paths
        "text_response": "...",      # optional text from model
        "thinking": "...",           # Pro model reasoning (when available)
        "timestamp": "2025-01-26T...",
    }
}

下游技能集成指南

模式 1:CLI 包装器(简单用法推荐)
# In your skill's script:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py "{prompt}" --model flash --ratio 16:9 -o output.png
模式 2:使用自定义默认值进行 Python 导入
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "google-genai>=1.0.0",
# ]
# ///

import sys
from pathlib import Path

NANOBANANA_DIR = Path("${CLAUDE_SKILL_DIR}/scripts")
sys.path.insert(0, str(NANOBANANA_DIR))
from generate import generate_image

def generate_thumbnail(prompt: str, output_path: str) -> dict:
    """Generate a YouTube thumbnail with project defaults."""
    return generate_image(
        prompt=prompt,
        output_path=output_path,
        aspect_ratio="16:9",
        image_size="2K",
        model="flash",
        max_retries=3,
    )
模式 3:带进度跟踪的批量生成
from batch_generate import batch_generate

def on_progress(completed, total, result):
    print(f"Progress: {completed}/{total}")

results = batch_generate(
    prompt="logo concept",
    count=20,
    output_dir="./logos",
    prefix="logo",
    model="flash",
    aspect_ratio="1:1",
    on_progress=on_progress,
)

successful = [r for r in results if r["success"]]
模式 4:为系列作品进行顺序生成

当下游技能需要多张风格一致的图像(例如,新闻简报配图、缩略图 A/B 变体)时,请使用锚点与参考图模式:

from generate import generate_image

# Step 1: Generate the style anchor
anchor = generate_image(
    prompt="warm illustration style, earth tones, soft gradients, clean lines",
    output_path="anchor.png",
    model="pro",
)

# Step 2: Generate each image in the series, referencing the anchor
subjects = ["laptop on desk with coffee", "person reading a book", "sunrise over mountains"]
series_paths = [anchor["path"]]

for i, subject in enumerate(subjects):
    result = generate_image(
        prompt=f"{subject}, matching the visual style and color palette of the reference image exactly",
        input_paths=[anchor["path"]],  # always include the anchor
        output_path=f"series_{i+1:02d}.png",
        model="pro",
    )
    if result["success"]:
        series_paths.append(result["path"])

完整的顺序生成模式见下文的顺序生成部分。

环境变量

变量描述默认值
GEMINI_API_KEYGoogle Gemini API 密钥必需
IMAGE_OUTPUT_DIR默认输出目录~/Downloads

功能

文本生成图像

根据文本描述创建图像。两种模型都擅长生成:

  • 照片级真实感图像
  • 艺术风格(像素艺术、插画等)
  • 产品摄影
  • 风景和场景
图像编辑

使用自然语言转换现有图像:

  • 风格迁移
  • 添加/移除对象
  • 更改背景
  • 调整颜色
多图参考

最多提供 14 张参考图,用于:

  • 保持系列作品的风格一致
  • 保持主体一致(同一角色,不同姿势)
  • 生成符合品牌风格的图像
  • 组合风格与主体
高分辨率输出
  • 1K — 生成速度快,适合草稿
  • 2K — 细节更丰富(2048px)
  • 4K — 画质最高(3840px),文字渲染效果最佳
Google 搜索接地

启用 --search,生成涉及以下内容且事实准确的图像:

  • 真实人物、地点、地标
  • 时事
  • 特定产品或品牌
自动重试

遇到速率限制错误时,会自动采用指数退避策略重试(默认:3 次)。调用方无需采取任何操作。

SynthID 水印须知

Gemini 生成的所有图像都包含不可见的 SynthID 数字水印。此功能会自动启用,无法关闭,并且水印在常见的转换(调整大小、裁剪、压缩)后仍会保留。对于要求输出不带水印的使用场景,请注意这一点。

顺序生成

使用顺序生成,让一系列图像保持视觉一致。核心方法:先生成一张锚点图像,然后在该系列中生成每张后续图像时,都将其作为参考(-i)传入。

模式 1:风格板锚定

生成一张用于确立系列视觉特征的锚点图像。后续所有图像都以此为参考。

适用场景: 新闻简报视觉系列、A/B 缩略图变体、保持品牌一致的图像批次。

工作流:

  1. 编写强调风格、配色和氛围的提示词,生成锚点图像:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py \
  "modern flat illustration style, warm earth tones, soft gradients, clean lines, \
  minimal detail, cozy atmosphere" \
  --model pro -o anchor.png
  1. 生成每张后续图像时,都以锚点图像为参考:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py \
  "a laptop on a desk with coffee, matching the visual style, color palette, \
  and lighting of the reference image exactly" \
  -i anchor.png --model pro -o image_01.png
  1. 对系列中的每张图像重复步骤 2,始终参考同一张锚点图像。

提示: 先用 Flash 快速拟定锚点图像,找到喜欢的风格后,再用 Pro 重新生成。

模式 2:主体一致性

在不同场景和姿势中,让相同角色或主体的外观保持一致。

适用场景: 出现在多个情境中的吉祥物、系列产品摄影、反复出现的角色。

工作流:

  1. 生成初始主体,并清晰、详细地描述其外观:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py \
  "a friendly robot mascot with round blue body, orange antenna, large expressive eyes, \
  simple geometric design, standing front-facing on white background" \
  --model pro -o subject_front.png
  1. 生成新场景时,以该主体为参考:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py \
  "the same robot character from the reference image, now sitting at a desk typing, \
  same proportions and colors, office background" \
  -i subject_front.png --model pro -o subject_office.png
  1. 若要提高一致性,可参考此前生成效果最佳的 2-3 张图像:
uv run ${CLAUDE_SKILL_DIR}/scripts/generate.py \
  "the same robot character from the reference images, now outdoors in a park, \
  same proportions and colors, waving at the viewer" \
  -i subject_front.png subject_office.png --model pro -o subject_park.png
模式 3:渐进式累积

在较长的系列中构建参考池,将每张成功生成的图像都加入参考,用于生成下一张图像。

适用场景: 需要让一致性贯穿整个系列的 5 张以上图像。

工作流:

  1. 生成锚点图像(与模式 1 的步骤 1 相同)。
  2. 生成图像 2,并参考锚点图像。
  3. 生成图像 3,并参考锚点图像和图像 2。
  4. 继续生成,在 -i 列表中保留最具代表性的 3-4 张参考图像。移除效果较弱的图像。

为何将参考图像数量限制为 3-4 张: 参考图像越多,风格信号越弱。模型会对所有输入取平均值——参考图像太多,生成结果就会失去连贯性。只保留最能体现目标风格的图像。

参考顺序很重要: 将风格锚点放在 -i 列表首位。模型对较早的参考图像赋予的权重略高。

最佳实践

提示词编写

优秀的提示词应包含:

  • 主体描述
  • 风格/美学
  • 光照和氛围
  • 构图细节
  • 配色方案

有关按类别划分的详细提示词模板和针对特定模型的技巧,请参阅 references/prompts.md。

批量生成技巧
  1. 使用 --model flash 进行探索性批量生成(速度更快、成本更低)
  2. 生成 10-20 个变体以探索不同选项
  3. 顺序请求之间默认间隔 3 秒,可避免触发速率限制
  4. 查看结果,并使用 Pro 模型迭代优化最佳候选项

速率限制

  • Gemini API 有使用配额(免费层级约为 10 RPM)
  • 自动指数退避重试可处理暂时性的速率限制
  • 对于大批量生成,请使用 --delay 5,或以适度的并发数使用 --parallel
  • 在 Google AI Studio 中查看配额

故障排除

“uv: command not found”

  • 安装 uv:curl -LsSf https://astral.sh/uv/install.sh | sh 或 brew install uv

“Error: google-genai package not installed”

  • 使用 uv run 替代 python3,以自动安装依赖项
  • 或手动安装:pip install -r ${CLAUDE_SKILL_DIR}/requirements.txt

“GEMINI_API_KEY environment variable not set”

  • 运行前在环境中设置 GEMINI_API_KEY

“No image in response”

  • 提示词可能触发了安全过滤器
  • 尝试改写提示词,避免敏感内容

“Rate limit exceeded after N retries”

  • 等待 30-60 秒后重试
  • 降低批处理并行度,或增加延迟时间
  • 检查 API 配额

batch_generate.py 中的导入错误

  • 脚本会自行设置路径;可从任意目录运行

未来功能

多轮对话式编辑 — Gemini API 支持有状态聊天会话,可用于迭代式图像编辑(例如:“调得更蓝一些” → “现在加顶帽子” → “缩小视野”)。这需要截然不同的有状态架构,目前尚未实现。目前没有下游技能需要此功能。

参考资料

评论

支持 Markdown