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/edit (37.5% off), Nano Banana 2 $0.05/edit (79% off official $0.24)

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/edit (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/edit (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 Functions
  • ✅ Supports both OpenAI-compatible format and Google native format
  • 🎭 Supports single/multi-image intelligent editing
  • 📐 Supports custom aspect ratios (16:9, 9:16, and 10 ratios)
  • 🖼️ Nano Banana 2 Exclusive: Supports 1K, 2K, 4K resolutions
  • ⚡ Completes editing in ~10 seconds on average
  • 💰 Great value: Nano Banana $0.025/edit (37.5% off), Nano Banana 2 $0.05/edit (79% off)

🔀 Two Calling Methods

FeatureOpenAI Compatible ModeGoogle Native Format
Endpoint/v1/chat/completions/v1beta/models/gemini-2.5-flash-image:generateContent
Output SizeDefault ratioSupports 10 aspect ratios
ResolutionFixed 1KNano Banana 2 supports 1K/2K/4K, Nano Banana fixed 1K
Multi-image✅ Supported✅ Supported
CompatibilityPerfect OpenAI SDK compatibilityRequires native calling
Return FormatBase64Base64
Image InputURL or Base64Base64 (inline_data)
💡 How to Choose?
  • If you only need default ratio images, use OpenAI Compatible Mode for simplicity
  • If you need custom aspect ratios (like 16:9, 9:16) or high resolution (2K/4K), use Google Native Format

📋 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/editBest quality, high resolution needed
Nano Banana🛡️ Stablegemini-2.5-flash-imageStableGemini 2.51K (Fixed)$0.025/editProduction 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/edit$0.24/edit79%1K/2K/4K~10s
Nano Bananagemini-2.5-flash-imagePer Request$0.025/edit$0.04/edit37.5%1K (Fixed)~10s
GPT-4o Editgpt-4oToken----~20s
DALL·E 2 Editdall-e-2Per Request-$0.018/image-FixedSlower
💰 Pricing Advantage
  • Nano Banana 2: $0.05/edit (LaoZhang API) vs $0.24/edit (Official), 79% cheaper
  • Nano Banana: $0.025/edit (LaoZhang API) vs $0.04/edit (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!

🚀 Quick Start

Prerequisites

1

Create Token

Log in to LaoZhang API Token Management and create a per-request billing tokenToken Creation Interface
2

Select Billing Method

Important: Must select “Per-Request Billing” type, not “Pay-As-You-Go”
3

Save Token

Copy the generated token, format is sk-xxxxxx
💰 Great Value Advantage
  • LaoZhang API: $0.025/edit (37.5% cheaper than official)
  • Official Price: $0.04/edit
  • Top-up Bonus: Top up $100 get +10% bonus
  • Exchange Rate Advantage: Total equals ~73% of official price

Method 1: OpenAI Compatible Mode

Single Image Edit - Curl

curl -X POST "https://api.laozhang.ai/v1/chat/completions" \
     -H "Authorization: Bearer sk-YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
    "model": "gemini-3-pro-image-preview",
    "stream": false,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "add a cute dog to this image"
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/your-image.jpg"
                    }
                }
            ]
        }
    ]
}'

Single Image Edit - Python SDK

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": [
                {
                    "type": "text",
                    "text": "add a cute dog to this image"
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/your-image.jpg"
                    }
                }
            ]
        }
    ]
)

# Extract and save image
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('edited.png', 'wb') as f:
        f.write(image_data)
    print("✅ Edited image saved: edited.png")

Multi-image Composition - Python SDK

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": [
                {
                    "type": "text",
                    "text": "merge these two images into one artistic composition"
                },
                {
                    "type": "image_url",
                    "image_url": {"url": "https://example.com/image1.jpg"}
                },
                {
                    "type": "image_url",
                    "image_url": {"url": "https://example.com/image2.jpg"}
                }
            ]
        }
    ]
)

# Extract and save image
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('merged.png', 'wb') as f:
        f.write(image_data)
    print("✅ Merged image saved: merged.png")

Method 2: Google Native Format (Custom Aspect Ratios)

Python Code Examples

💡 Progressive Relationship of Three Examples
Example 1 edits image → Example 2 uses it for style transfer → Example 3 combines the first two. Clear logic!
import requests
import base64

# ========== Configuration ==========
API_KEY = "sk-YOUR_API_KEY"

# Nano Banana 2 (supports 2K/4K)
API_URL = "https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent"
INPUT_IMAGE = "cat.jpg"  # Prepare a cat image
PROMPT = "add a cute wizard hat on this cat's head"
ASPECT_RATIO = "1:1"
IMAGE_SIZE = "2K"  # Nano Banana 2: 1K, 2K, 4K
# ============================

# Read and encode image
with open(INPUT_IMAGE, "rb") as f:
    image_b64 = base64.b64encode(f.read()).decode("utf-8")

headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

payload = {
    "contents": [{
        "parts": [
            {"text": PROMPT},
            {"inline_data": {"mime_type": "image/jpeg", "data": image_b64}}
        ]
    }],
    "generationConfig": {
        "responseModalities": ["IMAGE"],
        "imageConfig": {
            "aspectRatio": ASPECT_RATIO,
            "imageSize": IMAGE_SIZE
        }
    }
}

response = requests.post(API_URL, headers=headers, json=payload, timeout=180)
result = response.json()

# Save image
output_data = result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
with open("output.png", "wb") as f:
    f.write(base64.b64decode(output_data))

print("✅ Image saved: output.png")
import requests
import base64

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

INPUT_IMAGE = "output.png"  # Use the image generated from Example 1
PROMPT = "Transform this cat into Van Gogh Starry Night style oil painting"
ASPECT_RATIO = "1:1"
IMAGE_SIZE = "2K"  # Nano Banana 2: 1K, 2K, 4K
# ============================

# Read and encode image
with open(INPUT_IMAGE, "rb") as f:
    image_b64 = base64.b64encode(f.read()).decode("utf-8")

headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

payload = {
    "contents": [{
        "parts": [
            {"text": PROMPT},
            {"inline_data": {"mime_type": "image/png", "data": image_b64}}
        ]
    }],
    "generationConfig": {
        "responseModalities": ["IMAGE"],
        "imageConfig": {
            "aspectRatio": ASPECT_RATIO,
            "imageSize": IMAGE_SIZE
        }
    }
}

response = requests.post(API_URL, headers=headers, json=payload, timeout=180)
result = response.json()

# Save image
output_data = result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
with open("output_styled.png", "wb") as f:
    f.write(base64.b64decode(output_data))

print("✅ Image saved: output_styled.png")
import requests
import base64

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

# Use images generated from previous examples (outputs from Examples 1 and 2)
IMAGES = ["output.png", "output_styled.png"]
PROMPT = "Combine these two cat images into a single artistic composition"
ASPECT_RATIO = "16:9"
IMAGE_SIZE = "2K"  # Nano Banana 2: 1K, 2K, 4K
# ============================

# Build parts: text + multiple images
parts = [{"text": PROMPT}]

for img_path in IMAGES:
    with open(img_path, "rb") as f:
        img_b64 = base64.b64encode(f.read()).decode("utf-8")
    parts.append({"inline_data": {"mime_type": "image/png", "data": img_b64}})

headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

payload = {
    "contents": [{"parts": parts}],
    "generationConfig": {
        "responseModalities": ["IMAGE"],
        "imageConfig": {
            "aspectRatio": ASPECT_RATIO,
            "imageSize": IMAGE_SIZE
        }
    }
}

response = requests.post(API_URL, headers=headers, json=payload, timeout=180)
result = response.json()

# Save image
output_data = result["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
with open("output_mixed.png", "wb") as f:
    f.write(base64.b64decode(output_data))

print("✅ Image saved: output_mixed.png")

Complete Python Tool Script

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Gemini Image Editing Tool - Python Version
Upload local image + text description to generate new image with custom aspect ratios
"""

import requests
import base64
import os
import datetime
import mimetypes
from typing import Optional, Tuple

class GeminiImageEditor:
    """Gemini Image Editor"""

    # Supported aspect ratios
    SUPPORTED_ASPECT_RATIOS = [
        "21:9", "16:9", "4:3", "3:2", "1:1",
        "9:16", "3:4", "2:3", "5:4", "4:5"
    ]

    def __init__(self, api_key: str,
                 api_url: str = "https://api.laozhang.ai/v1beta/models/gemini-3-pro-image-preview:generateContent"):
        """
        Initialize image editor
        
        Args:
            api_key: API key
            api_url: API URL (using Google native Gemini API)
        """
        self.api_key = api_key
        self.api_url = api_url
        self.headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}"
        }

    def edit_image(self, image_path: str, prompt: str,
                   aspect_ratio: Optional[str] = "1:1",
                   output_dir: str = ".") -> Tuple[bool, str]:
        """
        Edit image and generate new image
        
        Args:
            image_path: Input image path
            prompt: Edit description (prompt)
            aspect_ratio: Aspect ratio like "16:9", "1:1" etc (default 1:1)
            output_dir: Output directory (default current directory)

        Returns:
            (success, message)
        """
        print(f"🚀 Starting image editing...")
        print(f"📁 Input image: {image_path}")
        print(f"📝 Edit description: {prompt}")
        print(f"📐 Aspect ratio: {aspect_ratio}")

        # Check if image file exists
        if not os.path.exists(image_path):
            return False, f"Image file not found: {image_path}"

        # Validate aspect ratio
        if aspect_ratio and aspect_ratio not in self.SUPPORTED_ASPECT_RATIOS:
            return False, f"Unsupported aspect ratio {aspect_ratio}. Supported: {', '.join(self.SUPPORTED_ASPECT_RATIOS)}"

        # Read and encode image
        try:
            with open(image_path, 'rb') as f:
                image_data = f.read()
            image_base64 = base64.b64encode(image_data).decode('utf-8')
            
            # Detect image type
            mime_type, _ = mimetypes.guess_type(image_path)
            if not mime_type or not mime_type.startswith('image/'):
                mime_type = 'image/jpeg'  # Default
            print(f"🎨 Image type: {mime_type}")
            
        except Exception as e:
            return False, f"Failed to read image: {str(e)}"

        # Generate output filename
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        output_file = os.path.join(output_dir, f"gemini_edited_{timestamp}.png")

        try:
            # Build request payload (Google native format)
            payload = {
                "contents": [{
                    "parts": [
                        {"text": prompt},
                        {
                            "inline_data": {
                                "mime_type": mime_type,
                                "data": image_base64
                            }
                        }
                    ]
                }]
            }

            # Add aspect ratio config
            if aspect_ratio:
                payload["generationConfig"] = {
                    "responseModalities": ["IMAGE"],
                    "imageConfig": {
                        "aspectRatio": aspect_ratio
                }
            }

            print("📡 Sending request to Gemini API...")

            # Send request
            response = requests.post(
                self.api_url,
                headers=self.headers,
                json=payload,
                timeout=120
            )

            if response.status_code != 200:
                return False, f"API request failed, status code: {response.status_code}"

            # Parse response
            result = response.json()
            
            # Extract image data
            if "candidates" not in result or len(result["candidates"]) == 0:
                return False, "Image data not found"

            candidate = result["candidates"][0]
            if "content" not in candidate or "parts" not in candidate["content"]:
                return False, "Response format error"

            parts = candidate["content"]["parts"]
            output_image_data = None

            for part in parts:
                if "inlineData" in part and "data" in part["inlineData"]:
                    output_image_data = part["inlineData"]["data"]
                    break

            if not output_image_data:
                return False, "Image data not found"

            # Decode and save image
            print("💾 Saving image...")
            decoded_data = base64.b64decode(output_image_data)

            os.makedirs(os.path.dirname(output_file) if os.path.dirname(output_file) else ".", exist_ok=True)

                 with open(output_file, 'wb') as f:
                f.write(decoded_data)

            file_size = len(decoded_data) / 1024  # KB
            print(f"✅ Image saved: {output_file}")
            print(f"📊 File size: {file_size:.2f} KB")

            return True, f"Successfully saved image: {output_file}"

        except requests.exceptions.Timeout:
            return False, "Request timeout (120 seconds)"
        except requests.exceptions.ConnectionError:
            return False, "Network connection error"
        except Exception as e:
            return False, f"Error: {str(e)}"

def main():
    """Main function - usage example"""

    # ========== Configuration ==========
    # 1. Set your API key
    API_KEY = "sk-YOUR_API_KEY"
    
    # 2. Input image path
    INPUT_IMAGE = "./input.jpg"  # Replace with your image path

    # 3. Input edit description (prompt)
    PROMPT = "add a cute cat next to the dog, keep the original composition"

    # 4. Select aspect ratio (optional)
    # Supported: 21:9, 16:9, 4:3, 3:2, 1:1, 9:16, 3:4, 2:3, 5:4, 4:5
    ASPECT_RATIO = "16:9"  # Widescreen
    # ASPECT_RATIO = "1:1"   # Square
    # ASPECT_RATIO = "9:16"  # Portrait

    # 5. Set output directory (optional)
    OUTPUT_DIR = "."  # Current directory
    # ============================

    print("="*60)
    print("Gemini Image Editing Tool")
    print("="*60)
    print(f"⏰ Start time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("="*60)

    # Create editor and edit image
    editor = GeminiImageEditor(API_KEY)
    success, message = editor.edit_image(
        image_path=INPUT_IMAGE,
        prompt=PROMPT,
        aspect_ratio=ASPECT_RATIO,
        output_dir=OUTPUT_DIR
    )

    # Display result
    print("\n" + "="*60)
    if success:
        print("🎉 Edit successful!")
        print(f"✅ {message}")
    else:
        print("❌ Edit failed")
        print(f"💥 {message}")
        print("\nSuggestions:")
        print("  1. Check if API key is correct")
        print("  2. Check if image path is correct")
        print("  3. Check network connection")
        print("  4. Check if prompt is reasonable")

    print(f"⏰ End time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("="*60)

if __name__ == "__main__":
    main()

🎯 Use Cases

Element Addition

Add new elements to existing images (people, animals, objects, etc.)

Style Conversion

Convert images to different art styles (oil painting, watercolor, cartoon, etc.)

Multi-image Composition

Merge multiple images into one creative work

Scene Transformation

Change image background, lighting, season, and other environmental factors

Product Display

Place product images in different scenarios for display

Creative Design

Provide rapid prototyping and creative inspiration for designers

💡 Best Practices

Editing Prompt Tips

1

Preserve Original

If you want to preserve most of the original, clearly state “keep the original composition” or similar
2

Specific Description

Describe in detail the elements to add or modify, including position, size, style, etc.
3

Style Consistency

If style consistency is needed, state “in the same style as the original image”
4

Multi-image Processing

When processing multiple images, clearly explain how to combine them (“merge”, “combine”, “place side by side”, etc.)

Aspect Ratio Selection Guide

Original RatioRecommended OutputNotes
Landscape photo16:9 or 4:3Suitable for horizontal display
Portrait photo9:16 or 3:4Suitable for phone wallpaper, posters
Square1:1Suitable for social media
Uncertain1:1Universal choice

❓ 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/edit$0.05/edit
Thinking Mode❌ No✅ Yes (built-in)
Search Grounding❌ No✅ Yes
Multi-image✅ 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/edit)
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: What image formats are supported?

Supports common image formats:
  • JPG/JPEG
  • PNG
  • WebP
  • GIF (static)
Recommend using JPG or PNG format for best results.

Q6: Is there a size limit?

  • Recommended size: Single image ≤ 5MB
  • Maximum size: ≤ 10MB
  • Oversized images increase processing time, recommend compressing before upload

Q7: How many images can be processed at once?

  • Nano Banana: Supports multiple images (recommend ≤ 3)
  • Nano Banana 2: Supports multiple images (up to 14, recommend ≤ 4)
  • Too many images affect generation quality and processing time

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

ModelLaoZhang APIOfficialSavings
Nano Banana 2$0.05/edit$0.24/edit79%
Nano Banana$0.025/edit$0.04/edit37.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-image support to 14 images (Nano Banana 2)
  • 💰 Updated pricing: Nano Banana 2 $0.05/edit (79% off official $0.24)
  • 📊 Added complete resolution table
  • 🔧 Updated model comparison and switching instructions

2024-12-XX

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

💡 Need Help?