Skip to main content
🚀 Nano Banana 2 is Now Live! Google’s latest generation image model Nano Banana 2 (internal code name) is officially released!
  • 🆕 Model Name: gemini-3-pro-image-preview
  • 🧠 Powered by Gemini 3: Stronger reasoning capabilities and image quality
  • 🔄 Seamless Switch: Same calling method as the old version, just change the model name
  • Legacy Supported: gemini-2.5-flash-image continues to serve stably
  • 📐 High-Res Support: Supports 1K, 2K, 4K resolutions (Nano Banana 2 only)
  • 💰 Pricing: Nano Banana $0.025/image (37.5% off), Nano Banana 2 $0.05/image (79% off official $0.24)

Prerequisites

1

Get API Key

Log in to laozhang.ai console to obtain your API key
2

Configure Billing Mode

Edit token settings and choose one of the following billing modes (same price for both):
  • Volume Priority (Recommended): Uses balance billing first, automatically switches when balance is insufficient. Suitable for most users
  • Pay-per-call: Direct deduction for each call. Suitable for strict budget control scenarios
Both modes have exactly the same price, Nano Banana $0.025/image, Nano Banana 2 $0.05/image, only the billing method differs.
Token Settings
If billing mode is not configured, API calls will fail. You must complete this configuration first!

Model Overview

Google’s Nano Banana series is the internal code name for its image generation technology, currently offering two generations:

🆕 Nano Banana 2 (Latest)

  • Model Name: gemini-3-pro-image-preview
  • Version: Preview
  • Technology: Based on Gemini 3 architecture, stronger reasoning
  • Features: Latest technology, superior image quality and details
  • Resolution: Supports 1K, 2K, 4K resolutions
  • Price: $0.05/image (79% cheaper than official $0.24)
  • Use Case: Best quality, high resolution, willing to try new features

🛡️ Nano Banana (Stable)

  • Model Name: gemini-2.5-flash-image
  • Version: Stable
  • Technology: Based on Gemini 2.5 architecture
  • Features: Stable and reliable, production recommended
  • Resolution: Fixed 1K (1024px), does not support imageSize parameter
  • Price: $0.025/image (37.5% cheaper than official $0.04)
  • Use Case: Production environments requiring stability
💡 Name Mapping
  • Nano Banana = gemini-2.5-flash-image (Stable)
  • Nano Banana 2 = gemini-3-pro-image-preview (Latest)
Both models use the exact same calling method, just change the model parameter to switch!

🌟 Common Features

Both generations support the following core capabilities:
🎉 Core Features
  • ✅ Supports both OpenAI-compatible format and Google native format
  • 🎨 Supports custom aspect ratios (16:9, 9:16, and 10 ratios)
  • 📐 Nano Banana 2 Exclusive: Supports 1K, 2K, 4K resolutions
  • ⚡ Generates high-quality images in ~10 seconds
  • 💰 Great value: Nano Banana $0.025/image (37.5% off), Nano Banana 2 $0.05/image (79% off)

🔀 Two Calling Methods

Gemini Flash Image supports two API endpoints, each with advantages:
FeatureOpenAI Compatible ModeGoogle Native Format
Endpoint/v1/chat/completions/v1beta/models/gemini-2.5-flash-image:generateContent
Model Namegemini-2.5-flash-imageSpecified in URL
Image SizeFixed 1:1Supports 10 aspect ratios
ResolutionFixed 1KNano Banana 2 supports 1K/2K/4K, Nano Banana fixed 1K
CompatibilityPerfect OpenAI SDK compatibilityRequires native calling
Return FormatBase64Base64
Use CaseQuick migration, simple needsCustom dimensions or high resolution needed
Aspect Ratio❌ No✅ 21:9, 16:9, 4:3, 3:2, 1:1, 9:16, 3:4, 2:3, 5:4, 4:5
💡 How to Choose?
  • If you only need square (1:1) images, use OpenAI Compatible Mode for simplicity
  • If you need widescreen (16:9), portrait (9:16), or other specific ratios/high resolution (2K/4K), use Google Native Format

🌟 Key Features

  • ⚡ Fast Response: ~10 seconds generation, significantly faster than OpenAI series
  • 💰 Great Value: Nano Banana $0.025/image (37.5% off), Nano Banana 2 $0.05/image (79% off)
  • 🔄 Dual Compatibility: Supports both OpenAI SDK and Google native format
  • 📐 Flexible Sizes: Google native format supports 10 aspect ratios
  • 🖼️ High Resolution: Nano Banana 2 supports 1K, 2K, 4K resolutions
  • 🧠 Thinking Mode: Nano Banana 2 has built-in reasoning, optimizes composition before generation (enabled by default)
  • 🌐 Search Grounding: Nano Banana 2 supports using Google Search to verify facts and generate images
  • 🎨 Multi-Reference: Supports up to 14 reference images (6 objects + 5 people, etc.)
  • 📦 Base64 Output: Returns base64-encoded image data directly, no secondary download needed
  • 🎨 Google Technology: Based on Google’s latest image generation technology, excellent quality

📋 Nano Banana Series Comparison

Series Model Comparison

ModelCode NameModel IDVersionTech BaseResolutionPriceRecommended Scenario
Nano Banana 2🆕 Latestgemini-3-pro-image-previewPreviewGemini 31K/2K/4K$0.05/imageBest quality, high resolution needed
Nano Banana🛡️ Stablegemini-2.5-flash-imageStableGemini 2.51K (Fixed)$0.025/imageProduction environment
Common Features: Same speed (~10s), same calling method

Comparison with Other Models

ModelModel IDBillingLaoZhang PriceOfficial PriceSavingsResolutionSpeed
Nano Banana 2gemini-3-pro-image-previewPer Request$0.05/image$0.24/image79%1K/2K/4K~10s
Nano Bananagemini-2.5-flash-imagePer Request$0.025/image$0.04/image37.5%1K (Fixed)~10s
GPT-Image-1gpt-image-1Per Token$10 input/$40 output per M---Medium
Flux Kontext Proflux-kontext-proPer Request$0.035/image$0.04/image12.5%-Fast
💰 Pricing Advantage
  • Nano Banana 2: $0.05/image (LaoZhang API) vs $0.24/image (Official), 79% cheaper
  • Nano Banana: $0.025/image (LaoZhang API) vs $0.04/image (Official), 37.5% cheaper
  • Top-up Bonus: Top up $100 get +10% bonus
  • Exchange Rate Advantage: RMB payment even more cost-effective
Nano Banana 2 has exceptional value on LaoZhang API!

Method 1: OpenAI Compatible Mode (1:1 Images)

🔄 Model Switching Guide
  • Use Nano Banana 2 (Latest): "model": "gemini-3-pro-image-preview"
  • Use Nano Banana (Stable): "model": "gemini-2.5-flash-image"
Both models use the exact same calling method, just modify the model field!

Basic Example - Curl

curl -X POST "https://api.laozhang.ai/v1/chat/completions" \
     -H "Authorization: Bearer $API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
    "model": "gemini-3-pro-image-preview",
    "stream": false,
    "messages": [
        {
            "role": "user",
            "content": "a beautiful sunset over mountains"
        }
    ]
}'

Python SDK Example

from openai import OpenAI
import base64
import re

client = OpenAI(
    api_key="sk-YOUR_API_KEY",
    base_url="https://api.laozhang.ai/v1"
)

response = client.chat.completions.create(
    model="gemini-3-pro-image-preview",  # Latest version, or use gemini-2.5-flash-image (stable)
    messages=[
        {
            "role": "user",
            "content": "a beautiful sunset over mountains"
        }
    ]
)

# Extract base64 image data
content = response.choices[0].message.content
match = re.search(r'!\[.*?\]\((data:image/png;base64,.*?)\)', content)

if match:
    base64_data = match.group(1).split(',')[1]
    image_data = base64.b64decode(base64_data)
    
    with open('output.png', 'wb') as f:
        f.write(image_data)
    print("✅ Image saved: output.png")

Method 2: Google Native Format (Custom Aspect Ratios + High Resolution)

🔄 Model Switching in Native Format In Google native format, the model name is specified in the URL path:
  • Nano Banana 2 (Latest): /v1beta/models/gemini-3-pro-image-preview:generateContent
  • Nano Banana (Stable): /v1beta/models/gemini-2.5-flash-image:generateContent

Supported Aspect Ratios

TypeAspect Ratio Options
Landscape21:9 (ultra-wide), 16:9 (widescreen), 4:3, 3:2
Square1:1
Portrait9:16 (vertical), 3:4, 2:3
Other5:4, 4:5

Supported Resolutions

💡 Resolution Support
  • Nano Banana 2 (gemini-3-pro-image-preview): Supports 1K, 2K, 4K resolutions
  • Nano Banana (gemini-2.5-flash-image): Fixed 1K (1024px), does not support imageSize parameter
Nano Banana 2 Resolution Options:
Aspect Ratio1K Resolution2K Resolution4K Resolution
1:11024×10242048×20484096×4096
16:91376×7682752×15365504×3072
9:16768×13761536×27523072×5504
4:31200×8962400×17924800×3584
3:4896×12001792×24003584×4800
21:91584×6723168×13446336×2688
3:21248×8322496×16644992×3328
2:3832×12481664×24963328×4992
5:41152×8962304×17924608×3584
4:5896×11521792×23043584×4608
💡 Resolution Selection Guide
  • 1K: Suitable for web display, social media, quick preview
  • 2K: Suitable for high-quality printing, professional display
  • 4K: Suitable for large-format printing, professional design, ultimate detail

Complete Curl Example (Text-to-Image 4K)

#!/bin/bash

# 1. Set API Key
export API_KEY="sk-YOUR_API_KEY"

# 2. Send request (Using Nano Banana 2 to generate 4K image)
curl -s -X POST "https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{
      "parts": [
        {"text": "A futuristic city skyline at sunset, high detailed, 4k"}
      ]
    }],
    "generationConfig": {
      "responseModalities": ["IMAGE"],
      "imageConfig": {
        "aspectRatio": "16:9",
        "imageSize": "4K"
      }
    }
  }' \
  | jq -r '.candidates[0].content.parts[0].inlineData.data' \
  | base64 --decode > output_4k.png

echo "✅ 4K image saved: output_4k.png"
💡 Model Switching
  • Use Nano Banana 2 (supports 4K): Change URL to gemini-3-pro-image-preview, add "imageSize": "4K"
  • Use Nano Banana (stable 1K): Change URL to gemini-2.5-flash-image, remove imageSize parameter

Complete Python Examples

💡 Progressive Logic: Three Connected Examples
Example 1 generates an image → Example 2 uses it for style transfer → Example 3 combines the first two images. Clear and intuitive!
We provide three complete, production-ready Python scripts:

1️⃣ Text-to-Image → Generate First Image

import requests
import base64
import os
import datetime

# --- API Key Configuration ---
API_KEY = "sk-YOUR_API_KEY"  # Replace with your API Key

# --- Parameters ---
PROMPT = "A cute orange cat"
ASPECT_RATIO = "1:1"
IMAGE_SIZE = "2K"  # Only Nano Banana 2 supports 1K, 2K, 4K
OUTPUT_DIR = "."  # Image save directory

# --- API Endpoint (Nano Banana 2) ---
API_URL = "https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent"

def generate_text_to_image(api_key, prompt, aspect_ratio, image_size, output_dir, api_url):
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {
            "responseModalities": ["IMAGE"],
            "imageConfig": {
                "aspectRatio": aspect_ratio,
                "imageSize": image_size
            }
        }
    }

    print(f"🚀 Generating text-to-image (Nano Banana 2, {image_size})...")
    print(f"📝 Prompt: {prompt}")
    print(f"📐 {aspect_ratio} | {image_size}")

    try:
        response = requests.post(api_url, headers=headers, json=payload, timeout=180)
        if response.status_code != 200:
            print(f"❌ API request failed: {response.status_code} - {response.text}")
            return False
        
        result = response.json()
        image_data_b64 = result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
        raw_data = base64.b64decode(image_data_b64)
        
        output_path = os.path.join(output_dir, "output.png")
        with open(output_path, "wb") as f:
            f.write(raw_data)
        
        print(f"✅ Image saved: {output_path}")
        return True
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return False

if __name__ == "__main__":
    generate_text_to_image(API_KEY, PROMPT, ASPECT_RATIO, IMAGE_SIZE, OUTPUT_DIR, API_URL)

2️⃣ Image-to-Image → Use First Image to Generate Second Image

import requests
import base64
import os
import datetime

# --- API Key Configuration ---
API_KEY = "sk-YOUR_API_KEY"  # Replace with your API Key

# --- Parameters ---
INPUT_IMAGE_PATH = "output.png"  # Use the image generated from Example 1
PROMPT = "Transform this cat into a Van Gogh Starry Night style oil painting"
ASPECT_RATIO = "1:1"
IMAGE_SIZE = "2K"
OUTPUT_DIR = "."

# --- API Endpoint (Nano Banana 2) ---
API_URL = "https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent"

def encode_image_to_base64(image_path):
    with open(image_path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")

def get_mime_type(image_path):
    ext = os.path.splitext(image_path)[1].lower()
    if ext in [".jpg", ".jpeg"]:
        return "image/jpeg"
    elif ext == ".png":
        return "image/png"
    else:
        return "application/octet-stream"  # Default type

def generate_image_to_image(api_key, input_image_path, prompt, aspect_ratio, image_size, output_dir, api_url):
    if not os.path.exists(input_image_path):
        print(f"❌ Error: Input image '{input_image_path}' not found.")
        return False

    encoded_image = encode_image_to_base64(input_image_path)
    mime_type = get_mime_type(input_image_path)

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
        }
    payload = {
        "contents": [{
            "parts": [
                {"text": prompt},
                {"inline_data": {"mime_type": mime_type, "data": encoded_image}}
            ]
        }],
        "generationConfig": {
            "responseModalities": ["IMAGE"],
            "imageConfig": {
                "aspectRatio": aspect_ratio,
                "imageSize": image_size
            }
        }
    }
    
    print(f"🚀 Generating image-to-image (Nano Banana 2, {image_size})...")
    print(f"📝 Prompt: {prompt}")
    print(f"📁 Input: {input_image_path}")

    try:
        response = requests.post(api_url, headers=headers, json=payload, timeout=180)
        if response.status_code != 200:
            print(f"❌ API request failed: {response.status_code} - {response.text}")
            return False
        
        result = response.json()
        image_data_b64 = result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
        raw_data = base64.b64decode(image_data_b64)
        
        output_path = os.path.join(output_dir, "output_styled.png")
        with open(output_path, "wb") as f:
            f.write(raw_data)
            
        print(f"✅ Image saved: {output_path}")
        return True
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return False

if __name__ == "__main__":
    generate_image_to_image(API_KEY, INPUT_IMAGE_PATH, PROMPT, ASPECT_RATIO, IMAGE_SIZE, OUTPUT_DIR, API_URL)

3️⃣ Multi-Image Mixing → Combine First and Second Images to Generate Third

import requests
import base64
import os
import datetime

# --- API Key Configuration ---
API_KEY = "sk-YOUR_API_KEY"  # Replace with your API Key

# --- Parameters ---
INPUT_IMAGE_PATHS = ["output.png", "output_styled.png"]  # Use images from Examples 1 and 2
PROMPT = "Combine these two cat images into a single artistic composition"
ASPECT_RATIO = "16:9"
IMAGE_SIZE = "2K"  # Nano Banana 2 supports 1K, 2K, 4K
OUTPUT_DIR = "."

# --- API Endpoint (Nano Banana 2) ---
API_URL = "https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent"

def encode_image_to_base64(image_path):
    with open(image_path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")

def get_mime_type(image_path):
    ext = os.path.splitext(image_path)[1].lower()
    if ext in [".jpg", ".jpeg"]:
        return "image/jpeg"
    elif ext == ".png":
        return "image/png"
    else:
        return "application/octet-stream"  # Default type

def generate_multi_image(api_key, input_image_paths, prompt, aspect_ratio, image_size, output_dir, api_url):
    parts = [{"text": prompt}]
    for path in input_image_paths:
        if not os.path.exists(path):
            print(f"❌ Error: Input image '{path}' not found. Please ensure the image is in the current directory.")
            return False
        encoded_image = encode_image_to_base64(path)
        mime_type = get_mime_type(path)
        parts.append({"inline_data": {"mime_type": mime_type, "data": encoded_image}})

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    payload = {
        "contents": [{"parts": parts}],
        "generationConfig": {
            "responseModalities": ["IMAGE"],
            "imageConfig": {
            "aspectRatio": aspect_ratio,
            "imageSize": image_size
            }
        }
    }

    print(f"🚀 Generating multi-image mix (Nano Banana 2, {image_size})...")
    print(f"📝 Prompt: {prompt}")
    print(f"📁 Input: {len(input_image_paths)} images")

    try:
        response = requests.post(api_url, headers=headers, json=payload, timeout=180)
        if response.status_code != 200:
            print(f"❌ API request failed: {response.status_code} - {response.text}")
            return False
        
        result = response.json()
        image_data_b64 = result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
        raw_data = base64.b64decode(image_data_b64)
        
        output_path = os.path.join(output_dir, "output_mixed.png")
        with open(output_path, "wb") as f:
            f.write(raw_data)
            
        print(f"✅ Image saved: {output_path}")
        return True
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return False

if __name__ == "__main__":
    generate_multi_image(API_KEY, INPUT_IMAGE_PATHS, PROMPT, ASPECT_RATIO, IMAGE_SIZE, OUTPUT_DIR, API_URL)
Features:
  • ✅ Complete, production-ready code
  • ✅ Direct copy-paste usage
  • ✅ Covers all three scenarios: text-to-image, single image-to-image, multi-image mixing
  • ✅ Easy model switching between Nano Banana and Nano Banana 2
📦 Complete Demo Script
View the complete demo script that strings together all three scenarios:
code-demo/gemini-image-API/complete_demo.py

Bash Script Example

#!/bin/bash

# ============================================================
# Gemini Image Generation Tool - Bash/Curl Version
# Supports Nano Banana (stable) and Nano Banana 2 (preview, 4K support)
# ============================================================

# ========== Configuration ==========
# 1. Set your API key
API_KEY="sk-YOUR_API_KEY"

# 2. Choose model and resolution
# Option 1: Nano Banana 2 (preview) - Supports 4K
MODEL="nano_banana2"
API_URL="https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent"
PROMPT="A futuristic cyberpunk city at night, neon lights, flying cars, highly detailed, 4k"
ASPECT_RATIO="16:9"
IMAGE_SIZE="4K"  # 1K, 2K, 4K

# Option 2: Nano Banana (stable) - Fixed 1K
# MODEL="nano_banana"
# API_URL="https://api.laozhang.ai/v1beta/models/gemini-2.5-flash-image:generateContent"
# PROMPT="a beautiful sunset over mountains"
# ASPECT_RATIO="16:9"
# IMAGE_SIZE=""  # Stable version doesn't support this parameter, leave empty

# 3. Set output filename
OUTPUT_FILE="gemini_${IMAGE_SIZE}_$(date +%Y%m%d_%H%M%S).png"
# ============================

# Check dependencies
if ! command -v jq &> /dev/null; then
    echo "❌ Error: jq tool is required"
    echo ""
    echo "Installation:"
    echo "  macOS:   brew install jq"
    echo "  Ubuntu:  sudo apt-get install jq"
    echo "  CentOS:  sudo yum install jq"
    echo ""
    exit 1
fi

echo "============================================================"
echo "Gemini Image Generation Tool"
echo "============================================================"
echo "⏰ Start time: $(date '+%Y-%m-%d %H:%M:%S')"
echo "============================================================"
echo "🚀 Starting image generation..."
echo "📝 Prompt: ${PROMPT}"
echo "📐 Aspect Ratio: ${ASPECT_RATIO}"
echo "📡 Sending request to Gemini API..."

# Build JSON request
if [ -n "$IMAGE_SIZE" ]; then
  # Include resolution parameter (Nano Banana 2 only)
  REQUEST_JSON=$(jq -n \
    --arg prompt "$PROMPT" \
    --arg ratio "$ASPECT_RATIO" \
    --arg size "$IMAGE_SIZE" \
    '{
      contents: [{
        parts: [{text: $prompt}]
      }],
      generationConfig: {
        responseModalities: ["IMAGE"],
        imageConfig: {
          aspectRatio: $ratio,
          imageSize: $size
        }
      }
    }')
  echo "🖼️  Resolution: ${IMAGE_SIZE}"
else
  # Without resolution parameter (Nano Banana)
  REQUEST_JSON=$(jq -n \
    --arg prompt "$PROMPT" \
    --arg ratio "$ASPECT_RATIO" \
    '{
      contents: [{
        parts: [{text: $prompt}]
      }],
      generationConfig: {
        responseModalities: ["IMAGE"],
        imageConfig: {
          aspectRatio: $ratio
        }
      }
    }')
  echo "🖼️  Resolution: 1K (fixed)"
fi

# Send request
RESPONSE=$(curl -s -X POST "${API_URL}" \
  -H "Authorization: Bearer ${API_KEY}" \
  -H "Content-Type: application/json" \
  -d "${REQUEST_JSON}")

# Check for errors
if echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
    echo "❌ API error:"
    echo "$RESPONSE" | jq -r '.error.message'
    exit 1
fi

# Extract and decode image
echo "🖼️  Extracting image data..."
IMAGE_DATA=$(echo "$RESPONSE" | jq -r '.candidates[0].content.parts[0].inlineData.data')

if [ -z "$IMAGE_DATA" ] || [ "$IMAGE_DATA" = "null" ]; then
    echo "❌ Failed to extract image data"
    echo "Response: $RESPONSE"
    exit 1
fi

# Decode base64 and save
echo "$IMAGE_DATA" | base64 --decode > "$OUTPUT_FILE"

    echo "============================================================"
echo "✅ Image generation complete!"
echo "📁 Saved to: $OUTPUT_FILE"
    echo "⏰ End time: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "============================================================"

🎯 Advanced Features (Nano Banana 2 Only)

Nano Banana 2 (gemini-3-pro-image-preview) offers several advanced features not available in the stable version:

1️⃣ Thinking Mode (Built-in Reasoning)

Nano Banana 2 has a built-in “thinking” process that optimizes composition before generating the final image. This feature is enabled by default and cannot be disabled. How it works:
  • Model generates 1-2 temporary images internally to test composition and logic
  • The last image in the “thinking” process is also the final rendered image
  • Improves image quality and adherence to complex prompts
No code changes needed - this feature works automatically!

2️⃣ Google Search Grounding

Use Google Search to verify facts and generate images based on real-time information (e.g., weather forecasts, stock charts, recent events). Example: Generate weather forecast visualization
import requests
import base64

API_KEY = "sk-YOUR_API_KEY"
API_URL = "https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent"

payload = {
    "contents": [{
        "parts": [{"text": "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart"}]
    }],
    "tools": [{"google_search": {}}],  # Enable Google Search
    "generationConfig": {
      "responseModalities": ["TEXT", "IMAGE"],
      "imageConfig": {"aspectRatio": "16:9"}
    }
}

response = requests.post(API_URL, headers={
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}, json=payload, timeout=180)

result = response.json()
image_data = result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
with open("weather_chart.png", "wb") as f:
    f.write(base64.b64decode(image_data))

3️⃣ Multi-Reference Images (Up to 14 Images)

Nano Banana 2 supports mixing up to 14 reference images:
  • Up to 6 high-fidelity object images for inclusion in the final image
  • Up to 5 portrait photos to maintain character consistency
Example: Combine multiple images
# See the "Multi-Image Mixing" example above
# You can pass up to 14 images in the "parts" array

📋 FAQ

Q1: What’s the difference between Nano Banana and Nano Banana 2?

FeatureNano BananaNano Banana 2
Model IDgemini-2.5-flash-imagegemini-3-pro-image-preview
VersionStablePreview
Tech BaseGemini 2.5Gemini 3
ResolutionFixed 1K (1024px)1K/2K/4K
Price$0.025/image$0.05/image
Thinking Mode❌ No✅ Yes (built-in)
Search Grounding❌ No✅ Yes
Multi-Reference✅ Yes (up to 3)✅ Yes (up to 14)
Speed~10s~10s
Recommended ForProduction, stability priorityBest quality, high resolution

Q2: Which model should I choose?

Choose Nano Banana (gemini-2.5-flash-image) if:
  • ✅ You need production stability
  • ✅ 1K resolution is sufficient
  • ✅ You want the lowest cost ($0.025/image)
Choose Nano Banana 2 (gemini-3-pro-image-preview) if:
  • ✅ You need high resolution (2K/4K)
  • ✅ You want the best image quality
  • ✅ You need advanced features (Thinking Mode, Search Grounding)
  • ✅ You’re willing to use a preview version

Q3: How do I switch between models?

Very simple! Just change the model name: OpenAI Compatible Mode:
# Nano Banana (stable)
model="gemini-2.5-flash-image"

# Nano Banana 2 (latest)
model="gemini-3-pro-image-preview"
Google Native Format:
# Nano Banana (stable)
https://api.laozhang.ai/v1beta/models/gemini-2.5-flash-image:generateContent

# Nano Banana 2 (latest)
https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent

Q4: How do I use 4K resolution?

4K is only supported by Nano Banana 2, use Google native format and add the imageSize parameter:
{
  "generationConfig": {
    "responseModalities": ["IMAGE"],
    "imageConfig": {
      "aspectRatio": "16:9",
      "imageSize": "4K"  // Must be uppercase "K"
    }
  }
}
Important: Must use uppercase “K” (1K, 2K, 4K), lowercase (1k) will be rejected.

Q5: Why is Nano Banana 2 so much cheaper on LaoZhang API?

ModelLaoZhang APIOfficialSavings
Nano Banana 2$0.05/image$0.24/image79%
Nano Banana$0.025/image$0.04/image37.5%
Nano Banana 2 has exceptional value on LaoZhang API! 79% cheaper than official pricing, plus top-up bonuses and exchange rate advantages.

📝 Changelog

2025-01-XX

  • 🆕 Added Nano Banana 2 (gemini-3-pro-image-preview) support
  • 🎨 Added 4K resolution support (Nano Banana 2 only)
  • 🧠 Added Thinking Mode (built-in reasoning, enabled by default)
  • 🌐 Added Google Search Grounding support
  • 🖼️ Expanded multi-reference image support to 14 images
  • 💰 Updated pricing: Nano Banana 2 $0.05/image (79% off official $0.24)
  • 📊 Added complete resolution table (10 aspect ratios × 3 resolutions)
  • 💻 Added complete Python code examples (text-to-image, single image-to-image, multi-image mixing)
  • 🔧 Added Bash script with model switching support

2024-12-XX

  • 🎉 Initial release of Nano Banana (gemini-2.5-flash-image)
  • 🎨 Support for 10 aspect ratios
  • 💰 Pricing: $0.025/image (37.5% off official)

💡 Need Help?