Nano Banana 2 Image Generation
Generates professional images with Nano Banana 2 (gemini-3.1-flash-image-preview).
Pro-level quality at Flash speed -- 512px to 4K, various aspect ratios, multilingual text rendering support.
When to Use This Skill
ALWAYS use this skill when the user:
- Asks for any image, graphic, illustration, or visual
- Wants a thumbnail, featured image, or banner
- Requests icons, diagrams, or patterns
- Asks to edit, modify, or restore a photo
- Uses words like: generate, create, make, draw, design, visualize
Do NOT attempt to generate images through any other method.
Prerequisites
1. Install Python SDK
pip install google-genai
2. Set API Key (paid required -- free keys cannot generate images)
export GEMINI_API_KEY="your-paid-api-key"
Or auto-load from project .env file.
Image Generation (Python SDK -- Default Method)
Basic Generation
import os
from google import genai
from google.genai import types
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
response = client.models.generate_content(
model="gemini-3.1-flash-image-preview",
contents="Your prompt here",
config=types.GenerateContentConfig(
response_modalities=["IMAGE", "TEXT"],
)
)
for part in response.candidates[0].content.parts:
if part.inline_data is not None:
with open("output.png", "wb") as f:
f.write(part.inline_data.data)
Advanced Options
Resolution Control
config=types.GenerateContentConfig(
response_modalities=["IMAGE", "TEXT"],
image_size="4K", # "512", "1K", "2K" (default), "4K"
)
Aspect Ratio
config=types.GenerateContentConfig(
response_modalities=["IMAGE", "TEXT"],
aspect_ratio="16:9", # "1:1", "16:9", "9:16", "4:3", "3:4", "4:1", "1:4", "8:1", "1:8"
)
Thinking Level (for complex prompts)
config=types.GenerateContentConfig(
response_modalities=["IMAGE", "TEXT"],
thinking_level="high", # "minimal" (default), "high", "dynamic"
)
Execution Pattern
Always follow this pattern when generating images:
Step 1: Determine Output Path
- If the project has an
assets/ directory, save there
- Otherwise save to current directory
- Name files appropriately (e.g.,
hero.png, thumbnail.png, logo.png)
- If using a dedicated
nanobanana-output/ output directory, adding it to .gitignore is recommended
Step 2: Load API Key
# Try environment variable -> .env file in order
import os
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
# Attempt to load from .env file
for env_path in [".env", "../.env", os.path.expanduser("~/.env")]:
if os.path.exists(env_path):
with open(env_path) as f:
for line in f:
if line.startswith("GEMINI_API_KEY="):
api_key = line.strip().split("=", 1)[1]
break
if api_key:
break
Step 3: Optimize Prompt
Good prompt structure:
- Subject: What to generate
- Details: Appearance, colors, textures
- Setting: Location, background, environment
- Style: Realistic, illustration, 3D render, etc.
- Lighting: Natural, dramatic, soft
- Composition: Close-up, wide shot
Step 4: Execute Generation + Verify Result
After generation, always verify the image using the Read tool and show it to the user.
Common Sizes
| Use Case |
Size |
Aspect Ratio |
| YouTube thumbnail |
1280x720 |
16:9 |
| Blog image |
1200x630 |
~16:9 |
| Square social |
1080x1080 |
1:1 |
| Twitter/X header |
1500x500 |
3:1 |
| Vertical story |
1080x1920 |
9:16 |
| GitHub README banner |
1280x640 |
16:9 |
Model Selection
| Model |
ID |
Use Case |
Price/Image |
| NB2 (default) |
gemini-3.1-flash-image-preview |
Fast generation, general purpose |
~$0.10 (2K) |
| NB Pro |
gemini-3-pro-image-preview |
Maximum fidelity, precise text |
~$0.20 |
| Imagen 4 |
imagen-4.0-generate-001 |
Photorealistic |
Separate |
Always default to NB2 -- Pro only when highest quality is needed.
Multi-Turn Editing
When modification is requested after image generation, edit conversationally:
# First generation
chat = client.chats.create(model="gemini-3.1-flash-image-preview")
response1 = chat.send_message(
"A red apple on a wooden table",
config=types.GenerateContentConfig(response_modalities=["IMAGE", "TEXT"])
)
# Edit (preserving previous context)
response2 = chat.send_message(
"Add a green leaf on top of the apple",
config=types.GenerateContentConfig(response_modalities=["IMAGE", "TEXT"])
)
Prompt Tips
- Be specific: Include style, mood, color, composition details
- When no text needed: Add "no text"
- Style reference: "editorial photography", "flat illustration", "3D render", "watercolor"
- Aspect ratio context: "wide banner", "square thumbnail", "vertical story"
- Complex scenes: Use thinking_level="high"
Troubleshooting
| Issue |
Solution |
| Quota exceeded |
Paid API key required -- free keys have 0 image generation quota |
| Text response instead of image |
Verify response_modalities=["IMAGE", "TEXT"] |
| 400 Bad Request |
Check prompt for policy violations, try simplifying |
| 429 Rate Limit |
Apply exponential backoff (2s, 4s, 8s...) |
| Model not found |
Verify model ID: gemini-3.1-flash-image-preview |
Gemini CLI Method (Alternative)
If Python SDK is unavailable, generate via Gemini CLI:
gemini -y -m gemini-3.1-flash-image-preview -p "Generate image and save as output.png: your prompt here"
Note: Gemini CLI requires Google account authentication, and the image generation model may require additional verification.
1---2name: nano-banana-23description: REQUIRED for all image generation requests. Generate and edit images using Nano Banana 2 (Gemini 3.1 Flash Image). Handles blog featured images, YouTube thumbnails, icons, diagrams, patterns, illustrations, photos, visual assets, graphics, artwork, pictures. Use this skill whenever the user asks to create, generate, make, draw, design, or edit any image or visual content.4---56# Nano Banana 2 Image Generation78Generates professional images with Nano Banana 2 (`gemini-3.1-flash-image-preview`).9Pro-level quality at Flash speed -- 512px to 4K, various aspect ratios, multilingual text rendering support.1011## When to Use This Skill1213ALWAYS use this skill when the user:14- Asks for any image, graphic, illustration, or visual15- Wants a thumbnail, featured image, or banner16- Requests icons, diagrams, or patterns17- Asks to edit, modify, or restore a photo18- Uses words like: generate, create, make, draw, design, visualize1920Do NOT attempt to generate images through any other method.2122## Prerequisites2324### 1. Install Python SDK25```bash26pip install google-genai27```2829### 2. Set API Key (paid required -- free keys cannot generate images)30```bash31export GEMINI_API_KEY="your-paid-api-key"32```3334Or auto-load from project `.env` file.3536## Image Generation (Python SDK -- Default Method)3738### Basic Generation39```python40import os41from google import genai42from google.genai import types4344client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])4546response = client.models.generate_content(47 model="gemini-3.1-flash-image-preview",48 contents="Your prompt here",49 config=types.GenerateContentConfig(50 response_modalities=["IMAGE", "TEXT"],51 )52)5354for part in response.candidates[0].content.parts:55 if part.inline_data is not None:56 with open("output.png", "wb") as f:57 f.write(part.inline_data.data)58```5960### Advanced Options6162#### Resolution Control63```python64config=types.GenerateContentConfig(65 response_modalities=["IMAGE", "TEXT"],66 image_size="4K", # "512", "1K", "2K" (default), "4K"67)68```6970#### Aspect Ratio71```python72config=types.GenerateContentConfig(73 response_modalities=["IMAGE", "TEXT"],74 aspect_ratio="16:9", # "1:1", "16:9", "9:16", "4:3", "3:4", "4:1", "1:4", "8:1", "1:8"75)76```7778#### Thinking Level (for complex prompts)79```python80config=types.GenerateContentConfig(81 response_modalities=["IMAGE", "TEXT"],82 thinking_level="high", # "minimal" (default), "high", "dynamic"83)84```8586## Execution Pattern8788**Always** follow this pattern when generating images:8990### Step 1: Determine Output Path91- If the project has an `assets/` directory, save there92- Otherwise save to current directory93- Name files appropriately (e.g., `hero.png`, `thumbnail.png`, `logo.png`)94- If using a dedicated `nanobanana-output/` output directory, adding it to `.gitignore` is recommended9596### Step 2: Load API Key97```python98# Try environment variable -> .env file in order99import os100api_key = os.environ.get("GEMINI_API_KEY")101if not api_key:102 # Attempt to load from .env file103 for env_path in [".env", "../.env", os.path.expanduser("~/.env")]:104 if os.path.exists(env_path):105 with open(env_path) as f:106 for line in f:107 if line.startswith("GEMINI_API_KEY="):108 api_key = line.strip().split("=", 1)[1]109 break110 if api_key:111 break112```113114### Step 3: Optimize Prompt115Good prompt structure:1161. **Subject**: What to generate1172. **Details**: Appearance, colors, textures1183. **Setting**: Location, background, environment1194. **Style**: Realistic, illustration, 3D render, etc.1205. **Lighting**: Natural, dramatic, soft1216. **Composition**: Close-up, wide shot122123### Step 4: Execute Generation + Verify Result124After generation, always verify the image using the Read tool and show it to the user.125126## Common Sizes127128| Use Case | Size | Aspect Ratio |129|----------|------|-------------|130| YouTube thumbnail | 1280x720 | 16:9 |131| Blog image | 1200x630 | ~16:9 |132| Square social | 1080x1080 | 1:1 |133| Twitter/X header | 1500x500 | 3:1 |134| Vertical story | 1080x1920 | 9:16 |135| GitHub README banner | 1280x640 | 16:9 |136137## Model Selection138139| Model | ID | Use Case | Price/Image |140|-------|-----|----------|------------|141| **NB2 (default)** | `gemini-3.1-flash-image-preview` | Fast generation, general purpose | ~$0.10 (2K) |142| NB Pro | `gemini-3-pro-image-preview` | Maximum fidelity, precise text | ~$0.20 |143| Imagen 4 | `imagen-4.0-generate-001` | Photorealistic | Separate |144145**Always default to NB2** -- Pro only when highest quality is needed.146147## Multi-Turn Editing148149When modification is requested after image generation, edit conversationally:150```python151# First generation152chat = client.chats.create(model="gemini-3.1-flash-image-preview")153response1 = chat.send_message(154 "A red apple on a wooden table",155 config=types.GenerateContentConfig(response_modalities=["IMAGE", "TEXT"])156)157158# Edit (preserving previous context)159response2 = chat.send_message(160 "Add a green leaf on top of the apple",161 config=types.GenerateContentConfig(response_modalities=["IMAGE", "TEXT"])162)163```164165## Prompt Tips1661671. **Be specific**: Include style, mood, color, composition details1682. **When no text needed**: Add "no text"1693. **Style reference**: "editorial photography", "flat illustration", "3D render", "watercolor"1704. **Aspect ratio context**: "wide banner", "square thumbnail", "vertical story"1715. **Complex scenes**: Use thinking_level="high"172173## Troubleshooting174175| Issue | Solution |176|-------|----------|177| Quota exceeded | **Paid API key required** -- free keys have 0 image generation quota |178| Text response instead of image | Verify `response_modalities=["IMAGE", "TEXT"]` |179| 400 Bad Request | Check prompt for policy violations, try simplifying |180| 429 Rate Limit | Apply exponential backoff (2s, 4s, 8s...) |181| Model not found | Verify model ID: `gemini-3.1-flash-image-preview` |182183## Gemini CLI Method (Alternative)184185If Python SDK is unavailable, generate via Gemini CLI:186```bash187gemini -y -m gemini-3.1-flash-image-preview -p "Generate image and save as output.png: your prompt here"188```189Note: Gemini CLI requires Google account authentication, and the image generation model may require additional verification.