
Nanobanana Image Gen
- 3 installs
- 1 repo stars
- Updated July 11, 2026
- simonlee2/claude-plugins
Helps with ai & agent building tasks.
About
nanobanana-image-gen is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- nanobanana-image-gen
- AI & Agent Building
- AI-coding skill
Nanobanana Image Gen by the numbers
- 3 all-time installs (skills.sh)
- Ranked #13,677 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/simonlee2/claude-plugins --skill nanobanana-image-genAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 1 |
| Last updated | July 11, 2026 |
| Repository | simonlee2/claude-plugins ↗ |
What it does
Helps with ai & agent building tasks.
Files
Nanobanana Image Generation
Overview
This skill enables image generation and editing using Google's Nanobanana model (google/nano-banana) through the Replicate API. Generate images from text prompts, transform existing images, apply style transfers, or create variations with precise control over aspect ratios and output formats.
Core Capabilities
1. Text-to-Image Generation
Generate images from natural language descriptions.
Example requests:
- "Generate an image of a sunset over snow-capped mountains"
- "Create a portrait of a cat wearing a bow tie in a Victorian setting"
- "Make me an abstract image with blue and purple swirls"
Process: 1. Extract the text description from the user's request 2. Determine appropriate aspect ratio (default: 1:1 for general images, 16:9 for landscapes, 2:3 for portraits) 3. Execute scripts/generate_image.py with the prompt 4. Save the generated image to the user's working directory
2. Image-to-Image Transformation
Transform or edit existing images using text prompts.
Example requests:
- "Make this photo look like a watercolor painting"
- "Transform this image to black and white with high contrast"
- "Turn this photo into an anime-style illustration"
- "Edit this image to make it look like it was taken at golden hour"
Process: 1. Ensure the input image is accessible (local file or URL) 2. If local file, it must be uploaded to a publicly accessible URL first (use appropriate upload method) 3. Extract the transformation instructions from the user's request 4. Execute scripts/generate_image.py with both prompt and image input 5. Save the transformed image to the user's working directory
3. Multi-Image Input
Use multiple images as references or inputs for generation.
Example requests:
- "Combine the style of this painting with the subject of this photo"
- "Generate an image that merges elements from these three images"
- "Create a variation that incorporates aspects from both of these images"
Process: 1. Ensure all input images are accessible as URLs 2. Provide all image URLs in the image_input array parameter 3. Execute scripts/generate_image.py with the prompt and multiple image inputs
4. Aspect Ratio Control
Generate images with specific dimensions for different use cases.
Available aspect ratios:
1:1- Square (social media posts, profile pictures)16:9- Widescreen (presentations, YouTube thumbnails)9:16- Vertical (mobile stories, TikTok)4:3- Standard (traditional photos)3:4- Portrait orientation21:9- Ultra-wide (cinematic)4:5- Instagram portrait5:4- Medium format2:3- Portrait photos3:2- Landscape photosmatch_input_image- Match input image dimensions (default when image input provided)
Example requests:
- "Generate a 16:9 banner image of a forest"
- "Create a square profile picture of a logo"
- "Make a vertical 9:16 image for Instagram stories"
Using the Generation Script
The scripts/generate_image.py script handles all Replicate API interactions with proper error handling and polling.
Basic usage:
python scripts/generate_image.py "a sunset over mountains" --output sunset.jpgWith image input:
python scripts/generate_image.py "make this look like a watercolor" \
--image-input https://example.com/photo.jpg \
--output watercolor.jpgWith multiple images:
python scripts/generate_image.py "combine these styles" \
--image-input https://example.com/img1.jpg \
--image-input https://example.com/img2.jpg \
--output combined.jpgCustom aspect ratio:
python scripts/generate_image.py "a wide landscape" \
--aspect-ratio 21:9 \
--output landscape.jpgPNG output:
python scripts/generate_image.py "transparent logo concept" \
--output-format png \
--output logo.pngImportant Implementation Details
Image URL Requirements
Replicate requires images to be uploaded to their file hosting service. The script automatically handles this:
1. If the input is a URL from any domain, the script downloads and re-uploads to Replicate 2. If the input is a local file path, the script reads and uploads to Replicate 3. This ensures compatibility with the Nanobanana model's requirements
Error Handling
The script includes comprehensive error handling:
- API authentication failures (missing or invalid
REPLICATE_API_KEY) - Network timeouts and connection errors
- Invalid image URLs or file paths
- Model execution failures with helpful error messages
Output Files
Generated images are saved to the specified output path. If no output path is specified, the script saves to ./generated_image_{timestamp}.jpg in the current directory.
Performance Considerations
- Image generation typically takes 5-15 seconds depending on complexity
- The script uses polling with appropriate intervals (configurable)
- Progress indicators show generation status
- Timeout is set to 5 minutes by default to handle complex generations
API Reference
For detailed information about the Nanobanana model parameters, capabilities, and best practices, refer to references/nanobanana-api.md.
Environment Setup
Ensure the REPLICATE_API_KEY environment variable is set:
export REPLICATE_API_KEY="your-api-key-here"Get an API key from https://replicate.com/account/api-tokens
Common Pitfalls
1. Image URLs not publicly accessible: Ensure input images are either publicly accessible URLs or properly uploaded to Replicate's file hosting 2. Missing API key: The script will fail if REPLICATE_API_KEY is not set in the environment 3. Aspect ratio mismatch: When using match_input_image, ensure at least one input image is provided 4. File path issues: Always use absolute paths or properly resolve relative paths for local image files
Best Practices
1. Descriptive prompts: More detailed prompts generally produce better results (e.g., "a serene mountain lake at sunset with pine trees in the foreground" vs "a lake") 2. Appropriate aspect ratios: Choose aspect ratios that match the intended use case 3. Image quality: When using image inputs, higher quality source images generally produce better results 4. Iterative refinement: Generate multiple variations by adjusting prompts to find the best result 5. Output format: Use PNG for images requiring transparency, JPG for photographs and general images (smaller file size)
Nanobanana Model API Reference
Model Information
Model ID: google/nano-banana Provider: Replicate Type: Image generation and editing Documentation: https://replicate.com/google/nano-banana
Model Capabilities
Nanobanana is Google's fast image generation model that excels at:
1. Text-to-image generation - Creating images from natural language descriptions 2. Image-to-image transformation - Editing and transforming existing images 3. Style transfer - Applying artistic styles to images 4. Multi-image input - Using multiple reference images to guide generation 5. Aspect ratio control - Precise control over output dimensions
Input Parameters
Required Parameters
prompt (string)
- Description: Text description of the desired image or transformation
- Best practices:
- Be specific and descriptive
- Include details about style, mood, lighting, composition
- For transformations, clearly describe the desired changes
- Examples:
- "A serene mountain landscape at sunset with pine trees in the foreground, photorealistic, 8k quality"
- "Transform this photo into a watercolor painting with soft pastel colors"
- "A futuristic cityscape with neon lights, cyberpunk style, rainy night"
Optional Parameters
image_input (array of URLs)
- Description: Input images to transform or use as reference
- Type: Array of strings (image URLs)
- Default:
[](empty array for text-to-image) - Format: Publicly accessible URLs or Replicate file URLs
- Multiple images: Supports multiple reference images
- Use cases:
- Image-to-image transformation
- Style transfer
- Image variation generation
- Multi-image composition
Important: Images must be uploaded to Replicate's file hosting service. The generation script handles this automatically.
aspect_ratio (string)
- Description: Aspect ratio of the generated image
- Type: String enum
- Default:
"match_input_image"(when images provided),"1:1"(for text-to-image) - Available options:
"match_input_image"- Match dimensions of input image (requires image input)"1:1"- Square (1024x1024) - Best for: profile pictures, social posts"16:9"- Widescreen (1344x768) - Best for: YouTube thumbnails, presentations, banners"9:16"- Vertical (768x1344) - Best for: Stories, TikTok, mobile wallpapers"4:3"- Standard (1152x896) - Best for: Traditional photos, presentations"3:4"- Portrait (896x1152) - Best for: Portrait photos"21:9"- Ultra-wide (1536x640) - Best for: Cinematic, ultra-wide displays"4:5"- Instagram portrait (1024x1280) - Best for: Instagram posts"5:4"- Medium format (1280x1024) - Best for: Medium format photography"2:3"- Portrait (896x1344) - Best for: Portrait photography"3:2"- Landscape (1344x896) - Best for: Landscape photography
output_format (string)
- Description: Format of the output image
- Type: String enum
- Default:
"jpg" - Available options:
"jpg"- JPEG format, smaller file size, no transparency"png"- PNG format, larger file size, supports transparency- When to use PNG: Logos, graphics requiring transparency, images with text
- When to use JPG: Photographs, general images, when file size matters
Output
The model returns a single output object with a url() method that provides the generated image URL.
Output structure:
output = {
"url": lambda: "https://replicate.delivery/pbxt/..."
}Accessing the image:
image_url = output.url()Performance Characteristics
Generation Times
- Simple prompts: 5-10 seconds
- Complex prompts: 10-15 seconds
- Image-to-image: 8-12 seconds
- Multi-image input: 12-18 seconds
Polling Configuration
- Recommended interval: 1000ms (1 second)
- Timeout: 300 seconds (5 minutes)
- Mode: Poll mode with intervals
Best Practices
Prompt Engineering
1. Be specific and descriptive
- Good: "A majestic lion with a golden mane sitting on a rocky outcrop at sunset, dramatic lighting, photorealistic, 8k"
- Poor: "A lion"
2. Include style modifiers
- Examples: "photorealistic", "oil painting", "watercolor", "anime style", "cyberpunk", "impressionist"
3. Specify lighting and mood
- Examples: "golden hour lighting", "dramatic shadows", "soft diffused light", "neon glow"
4. Add quality indicators
- Examples: "8k quality", "highly detailed", "professional photography", "cinematic"
5. For transformations, be clear about desired changes
- Good: "Transform this photo into a watercolor painting with soft pastel colors and visible brush strokes"
- Poor: "Make it look artistic"
Image Input Best Practices
1. Image quality: Higher quality source images produce better results 2. Image size: Optimal input size is 1024px on the longest side 3. Multiple images: When using multiple inputs, ensure they're thematically related 4. URL accessibility: Ensure image URLs are publicly accessible
Aspect Ratio Selection
Choose aspect ratios based on the intended use:
- Social media: 1:1 (Instagram), 9:16 (Stories), 4:5 (Instagram portrait)
- Video thumbnails: 16:9 (YouTube, streaming platforms)
- Photography: 3:2 (landscape), 2:3 (portrait), 4:3 (standard)
- Cinematic: 21:9 (ultra-wide)
- Presentations: 16:9 (modern), 4:3 (traditional)
Error Handling
Common errors and solutions:
1. "Invalid image URL"
- Ensure image URLs are publicly accessible
- Upload images to Replicate's file hosting first
2. "API key not found"
- Set the
REPLICATE_API_KEYenvironment variable - Verify the API key is valid
3. "Request timeout"
- Increase timeout duration for complex generations
- Simplify the prompt or reduce image input count
4. "Model prediction failed"
- Check prompt for inappropriate content
- Verify input images are valid and accessible
- Try with a simpler prompt
Rate Limits
Replicate enforces rate limits based on account tier:
- Free tier: Limited concurrent predictions
- Pro tier: Higher concurrency limits
- Enterprise: Custom limits
Handle rate limits by:
- Implementing exponential backoff
- Queueing requests
- Monitoring API response headers
Cost Considerations
Pricing is based on:
- Prediction run time: Billed per second
- Input image size: Larger inputs may cost more
- Output resolution: Higher resolutions may increase cost
Check current pricing at: https://replicate.com/google/nano-banana
Example API Calls
Text-to-Image
import replicate
output = replicate.run(
"google/nano-banana",
input={
"prompt": "A majestic mountain landscape at sunset",
"aspect_ratio": "16:9",
"output_format": "jpg"
}
)
image_url = output.url()Image-to-Image Transformation
output = replicate.run(
"google/nano-banana",
input={
"prompt": "Transform into a watercolor painting",
"image_input": ["https://replicate.delivery/pbxt/..."],
"aspect_ratio": "match_input_image",
"output_format": "jpg"
}
)
image_url = output.url()Multi-Image Input
output = replicate.run(
"google/nano-banana",
input={
"prompt": "Combine the style from the first image with the subject from the second",
"image_input": [
"https://replicate.delivery/pbxt/style.jpg",
"https://replicate.delivery/pbxt/subject.jpg"
],
"aspect_ratio": "1:1",
"output_format": "jpg"
}
)
image_url = output.url()Troubleshooting
Common Issues
1. Slow generation times
- Normal for complex prompts
- Use simpler prompts or fewer input images
- Check Replicate status page for service issues
2. Poor quality results
- Add quality modifiers to prompt ("8k", "highly detailed")
- Use higher quality input images
- Be more specific in the prompt
3. Unexpected style or content
- Refine the prompt with more specific details
- Add negative prompts if supported in future versions
- Adjust aspect ratio to match intended composition
4. File upload failures
- Verify image files are valid
- Check file size limits (typically 10MB max)
- Ensure network connectivity
Additional Resources
- Replicate Documentation: https://replicate.com/docs
- Nanobanana Model Page: https://replicate.com/google/nano-banana
- API Reference: https://replicate.com/docs/reference/http
- Python Client: https://github.com/replicate/replicate-python
- Rate Limits: https://replicate.com/docs/topics/rate-limits
#!/usr/bin/env python3
"""
Nanobanana Image Generation Script
Generates or edits images using Google's Nanobanana model via Replicate API.
Supports text-to-image generation, image-to-image transformation, and multi-image input.
"""
import argparse
import os
import sys
import time
from datetime import datetime
from typing import List, Optional
from urllib.parse import urlparse
try:
import replicate
from replicate.exceptions import ReplicateError
except ImportError:
print("Error: replicate package not installed")
print("Install it with: pip install replicate")
sys.exit(1)
# Model configuration
MODEL_ID = "google/nano-banana"
POLLING_INTERVAL = 1 # seconds
TIMEOUT = 300 # seconds (5 minutes)
# Valid aspect ratios
VALID_ASPECT_RATIOS = [
"match_input_image", "1:1", "2:3", "3:2", "3:4", "4:3",
"4:5", "5:4", "9:16", "16:9", "21:9"
]
# Valid output formats
VALID_OUTPUT_FORMATS = ["jpg", "png"]
def validate_environment():
"""Validate that required environment variables are set."""
# Check for either REPLICATE_API_KEY or REPLICATE_API_TOKEN
api_key = os.environ.get("REPLICATE_API_KEY") or os.environ.get("REPLICATE_API_TOKEN")
if not api_key:
print("Error: REPLICATE_API_KEY or REPLICATE_API_TOKEN environment variable not set")
print("Get an API key from: https://replicate.com/account/api-tokens")
print("Then set it with: export REPLICATE_API_KEY='your-api-key'")
print("Or: export REPLICATE_API_TOKEN='your-api-token'")
sys.exit(1)
return api_key
def is_url(path: str) -> bool:
"""Check if a path is a URL."""
try:
result = urlparse(path)
return all([result.scheme, result.netloc])
except Exception:
return False
def upload_image_to_replicate(image_path: str, client: replicate.Client) -> str:
"""
Upload an image to Replicate's file hosting.
Args:
image_path: Local file path or URL
client: Replicate client instance
Returns:
Replicate-hosted image URL
"""
try:
print(f" Uploading image: {image_path}")
if is_url(image_path):
# Download from URL and re-upload to Replicate
import requests
response = requests.get(image_path, timeout=30)
response.raise_for_status()
# Determine filename from URL
filename = os.path.basename(urlparse(image_path).path) or "image"
# Create file object
from io import BytesIO
content_type = response.headers.get("content-type", "application/octet-stream")
file_data = BytesIO(response.content)
file_data.name = filename
# Upload to Replicate
uploaded_file = client.files.create(file_data, metadata={"original_url": image_path})
else:
# Upload local file
if not os.path.exists(image_path):
raise FileNotFoundError(f"Image file not found: {image_path}")
with open(image_path, "rb") as f:
uploaded_file = client.files.create(f)
print(f" ✓ Uploaded successfully")
return uploaded_file.urls.get
except Exception as e:
print(f" ✗ Upload failed: {e}")
raise
def generate_image(
prompt: str,
image_inputs: Optional[List[str]] = None,
aspect_ratio: str = "1:1",
output_format: str = "jpg",
output_path: Optional[str] = None,
) -> str:
"""
Generate or edit an image using Nanobanana.
Args:
prompt: Text description of the desired image
image_inputs: Optional list of input image paths or URLs
aspect_ratio: Aspect ratio of the output image
output_format: Output format (jpg or png)
output_path: Path to save the generated image
Returns:
URL of the generated image
"""
# Validate environment
api_key = validate_environment()
# Create Replicate client
client = replicate.Client(api_token=api_key)
# Prepare input parameters
input_params = {
"prompt": prompt,
"aspect_ratio": aspect_ratio,
"output_format": output_format,
}
# Upload input images if provided
if image_inputs:
print(f"Uploading {len(image_inputs)} input image(s)...")
hosted_images = []
for img in image_inputs:
hosted_url = upload_image_to_replicate(img, client)
hosted_images.append(hosted_url)
input_params["image_input"] = hosted_images
print()
# Run the model
print(f"Generating image with Nanobanana...")
print(f" Prompt: {prompt}")
print(f" Aspect ratio: {aspect_ratio}")
print(f" Output format: {output_format}")
if image_inputs:
print(f" Input images: {len(image_inputs)}")
print()
try:
start_time = time.time()
# Run prediction with polling
print(" Starting prediction...")
output = client.run(
MODEL_ID,
input=input_params,
)
elapsed_time = time.time() - start_time
print(f"✓ Generation completed in {elapsed_time:.1f}s")
# Extract image URL - Replicate returns a FileOutput object or string
if isinstance(output, str):
image_url = output
elif hasattr(output, 'url') and callable(output.url):
image_url = output.url()
elif hasattr(output, 'url'):
image_url = output.url
else:
# Try to get URL from dict-like object
image_url = str(output)
print(f" Image URL: {image_url}")
# Download and save if output path specified
if output_path:
print(f"\nDownloading image to: {output_path}")
import requests
response = requests.get(image_url, timeout=30)
response.raise_for_status()
# Create output directory if needed
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
with open(output_path, "wb") as f:
f.write(response.content)
print(f"✓ Image saved successfully")
return image_url
except ReplicateError as e:
print(f"✗ Replicate API error: {e}")
sys.exit(1)
except Exception as e:
print(f"✗ Generation failed: {e}")
sys.exit(1)
def main():
"""Main entry point for the script."""
parser = argparse.ArgumentParser(
description="Generate or edit images using Google's Nanobanana model",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Basic text-to-image
python generate_image.py "a sunset over mountains" --output sunset.jpg
# Image-to-image transformation
python generate_image.py "make it look like a watercolor painting" \\
--image-input photo.jpg --output watercolor.jpg
# Multiple input images
python generate_image.py "combine these styles" \\
--image-input style1.jpg --image-input style2.jpg --output combined.jpg
# Custom aspect ratio
python generate_image.py "a wide landscape" \\
--aspect-ratio 21:9 --output landscape.jpg
# PNG output
python generate_image.py "a logo design" \\
--output-format png --output logo.png
"""
)
parser.add_argument(
"prompt",
help="Text description of the image to generate or transformation to apply"
)
parser.add_argument(
"--image-input",
action="append",
dest="image_inputs",
help="Input image path or URL (can be specified multiple times for multi-image input)"
)
parser.add_argument(
"--aspect-ratio",
choices=VALID_ASPECT_RATIOS,
default="1:1",
help="Aspect ratio of the output image (default: 1:1)"
)
parser.add_argument(
"--output-format",
choices=VALID_OUTPUT_FORMATS,
default="jpg",
help="Output format (default: jpg)"
)
parser.add_argument(
"--output",
"-o",
help="Path to save the generated image (default: generated_image_<timestamp>.jpg)"
)
args = parser.parse_args()
# Generate default output path if not specified
if not args.output:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
args.output = f"generated_image_{timestamp}.{args.output_format}"
# Adjust aspect ratio default for image inputs
if args.image_inputs and args.aspect_ratio == "1:1":
args.aspect_ratio = "match_input_image"
# Generate the image
print("=" * 60)
print("Nanobanana Image Generation")
print("=" * 60)
print()
try:
image_url = generate_image(
prompt=args.prompt,
image_inputs=args.image_inputs,
aspect_ratio=args.aspect_ratio,
output_format=args.output_format,
output_path=args.output,
)
print()
print("=" * 60)
print("✓ Success!")
print(f"Image URL: {image_url}")
print(f"Saved to: {args.output}")
print("=" * 60)
except KeyboardInterrupt:
print("\n\nOperation cancelled by user")
sys.exit(1)
except Exception as e:
print(f"\n✗ Failed: {e}")
sys.exit(1)
if __name__ == "__main__":
main()