🤖 AI Hot

Nano Banana 2: Edit Images With Code via OpenRouter

A
Alex Chen

If you are putting together a best AI tools 2026 shortlist for programmatic image work, Nano Banana 2 deserves a spot near the top of the editing column. It is Google’s Gemini 3.1 Flash Image model — “Nano Banana” is just the nickname the community stuck on the Gemini image family — and through OpenRouter it is reachable with a single API call, no Google Cloud project, no separate SDK, no provider lock-in. You send a source image and a text instruction, and the edited image comes back as base64 in the response. This tutorial walks through the exact code, the pricing, the model variants, and the pitfalls.

What Nano Banana 2 actually is

The name is worth decoding once, because the model slug on OpenRouter is not “nano-banana.” Nano Banana is the nickname for Google’s Gemini image models. Nano Banana 2 is google/gemini-3.1-flash-image, the default fast model in the family. The full family has four current members:

  • Nano Banana 2 — google/gemini-3.1-flash-image, the default, fast and high quality.
  • Nano Banana 2 Lite — google/gemini-3.1-flash-lite-image, the cheapest and fastest.
  • Nano Banana Pro — google/gemini-3-pro-image, slower and higher quality.
  • Nano Banana (original) — google/gemini-2.5-flash-image, the older model the nickname started with.

Because you reach all of them through one API and one request shape, switching from one to another is a one-field change. That is the real reason to route this through OpenRouter rather than Google’s own API: you keep a single integration point and can compare providers or models without rewriting your client.

Editing vs generation: know which one you are doing

There is a clean line between the two operations, and it matters because the request is shaped differently. Image editing changes an existing image. Image generation creates a new image from text. Every editing request includes a source image in input_references and an instruction that says what to change and what to keep. If your request has no source image and works from a text prompt alone, that is generation.

The request shape for editing is the same in every language. Put the reference image in input_references and the instruction in prompt. Read the edited image from data[0].b64_json and decode it to disk. That is the whole thing.

Prerequisites

You need three things before you start:

  1. An OpenRouter API key from the keys page, and the base URL https://openrouter.ai/api/v1.
  2. An HTTP client. The examples below use Python requests and TypeScript fetch, but curl or the OpenRouter SDK work too — any client that sends a JSON POST with an Authorization header.
  3. A source image, either a local file or a public URL.

Keep the API key in an environment variable rather than hardcoding it. Every example below assumes OPENROUTER_API_KEY is set.

The code: Python, editing a local image

Here is a working request that encodes a local file as a base64 data URL and sends it with an edit instruction:

import os
import base64
import requests

api_key = os.environ["OPENROUTER_API_KEY"]
path = "source.png"

with open(path, "rb") as f:
    b64 = base64.b64encode(f.read()).decode("utf-8")
source = f"data:image/png;base64,{b64}"

resp = requests.post(
    "https://openrouter.ai/api/v1/images",
    headers={"Authorization": f"Bearer {api_key}"},
    json={
        "model": "google/gemini-3.1-flash-image",
        "prompt": "Add a red wool scarf around the person's neck. Keep everything else the same.",
        "input_references": [
            {"type": "image_url", "image_url": {"url": source}}
        ],
    },
)

item = resp.json()["data"][0]
with open("edited.png", "wb") as f:
    f.write(base64.b64decode(item["b64_json"]))

The input_references field takes either a base64 data URL or an HTTP(S) URL. If your image is already hosted publicly, pass the link directly and skip the encoding step — it keeps the request body small:

json={
    "model": "google/gemini-3.1-flash-image",
    "prompt": "Change the background to a snowy street at night. Keep the subject exactly as is.",
    "input_references": [
        {"type": "image_url", "image_url": {"url": "https://example.com/source.png"}}
    ],
}

Use the URL form when the image is public and hosted; use base64 for local or private files.

TypeScript and the SDK

The request body is identical in TypeScript, using fetch:

const apiKey = process.env.OPENROUTER_API_KEY!;
const source = "data:image/png;base64," + Buffer.from(await fs.readFile("source.png")).toString("base64");

const resp = await fetch("https://openrouter.ai/api/v1/images", {
  method: "POST",
  headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "google/gemini-3.1-flash-image",
    prompt: "Add a red wool scarf around the person's neck. Keep everything else the same.",
    input_references: [{ type: "image_url", image_url: { url: source } }],
  }),
});
const data = await resp.json();
const item = data.data[0];
await fs.writeFile("edited.png", Buffer.from(item.b64_json, "base64"));

If you prefer a typed client, the OpenRouter SDK has an images resource that calls the same endpoint:

from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
)

result = client.images.generate(
    model="google/gemini-3.1-flash-image",
    prompt="Add a red wool scarf around the person's neck. Keep everything else the same.",
    input_references=[{"type": "image_url", "image_url": {"url": source}}],
)

Because OpenRouter is OpenAI-compatible, most SDKs work by swapping the base URL. The only thing that changes between models is the slug.

Multi-step editing: stack small changes

One edit will not always give you what you want, and the model does not remember your earlier prompts. To run another pass, take the b64_json value from the response, turn it into a data URL, and pass it in as the next input_references. Each call edits the last result, so earlier changes carry forward — but you must repeat the parts it should leave alone in each new prompt.

Give one instruction per call. Small edits are easier to check and easier to redo when they come back wrong. Describe the change first, then name what to preserve: “Change the background to a snowy street at night. Keep the subject exactly as is.” That ordering matters more than people expect.

Where Nano Banana 2 fits in an AI agent framework comparison

If you are doing an AI agent framework comparison and wondering how image editing slots in, the answer is: as a tool call, not a model you reason with. Most agent frameworks — LangChain, CrewAI, AutoGen, and the OpenAI-compatible tool layers — can call an external HTTP endpoint as a function. Because the OpenRouter edit endpoint takes a clean JSON payload and returns base64, wrapping it as a tool is trivial: the agent decides “edit this image,” calls your wrapper, and receives a path to the edited file.

One caveat to plan around: the Nano Banana 2 endpoint on OpenRouter does not accept tools, so function calling is unavailable on the model itself. That is fine, because you are not asking Nano Banana to call tools — you are calling it as a tool from a reasoning model. Keep that separation explicit in your design. The reasoning model orchestrates; Nano Banana edits; the edited image goes back into context as an input.

Pricing and providers

Nano Banana 2 is served by two providers on OpenRouter — Google AI Studio and Google Vertex — and the pricing is identical across them: $0.50 per million input tokens, $3.00 per million output tokens, and $60.00 per million image output tokens. Web Search grounding, if you use it, runs $14.00 per 1,000 calls.

The two providers differ slightly on latency and uptime. Google AI Studio measured about 17.7 seconds end-to-end latency at 100% uptime in the most recent window; Google Vertex about 19.4 seconds at 99.76%. OpenRouter routes to the best available provider with automatic failover, and you can pin or exclude providers if you need deterministic routing.

For cost control, the cheapest member of the family is Nano Banana 2 Lite (google/gemini-3.1-flash-lite-image). The highest quality is Nano Banana Pro (google/gemini-3-pro-image), which you should reach for when fidelity beats latency.

Tips and pitfalls

Supported formats. Gemini accepts image/png, image/jpeg, image/webp, image/heic, and image/heif inputs. Supported formats vary by model, so check the model page before you send an unusual file.

Reference image limit. Up to 14 reference images can be attached to a single editing request, which is plenty for multi-image composition work but easy to forget if you are porting code from a model that accepted more.

Output resolution. Nano Banana 2 outputs at 1K resolution across 14 aspect ratios, and every image carries an invisible SynthID watermark identifying it as AI-generated. If watermarking matters for your compliance story, know that it is on by default.

Watch response errors and rate limits. Add a retry with backoff around your requests, log the cost per call, and keep the key in an environment variable. Oversized files and transient 429s are the two most common failure modes in production.

Editing support varies by model. Before you swap the model field to something like openai/gpt-5-image, confirm that the target model accepts image input and supports the same input_references shape. Not every model on OpenRouter edits the same way.

Edit recipes that work reliably

Some instructions recur across projects, so it is worth having a tested phrasing for each.

Recolor or restyle a product. “Change the mug from blue to matte black. Keep the lighting, angle, and background identical.” Naming the exact object plus what must stay fixed keeps the model from repainting the whole scene.

Swap a background. “Replace the background with a clean studio backdrop. Keep the subject’s pose and clothing exactly as is.” This is the highest-success edit in the family, and the one I reach for most.

Remove an object. “Remove the power lines from the sky. Leave the rest of the photo unchanged.” Small removals are reliable; large structural removals sometimes leave artifacts, so check the result before shipping.

Fix text. “Correct the sign to read ‘OPEN’ in the same font and color. Change nothing else.” Typography is the hardest thing for image models to get right, so expect to iterate once or twice on any text-bearing edit.

Compose from multiple references. With up to 14 reference images, you can pass a subject image, a background image, and a style reference in one request and ask the model to combine them. State each source’s role explicitly in the prompt so the model does not guess.

The common thread: name the change first, then name what to preserve, and keep each instruction to a single operation.

Limitations and caveats

Nano Banana 2 is a hosted, closed-weights model — there is no self-hosting option, and you are routing requests through OpenRouter (or Google) rather than running anything locally. That is the right trade for most editing workloads, but it is a real constraint if you need data residency, air-gapped inference, or fine-tuning.

The model returns base64 rather than a file handle, so large images mean large response bodies and some memory pressure on your client. For very large batches, prefer the URL input form to keep requests small and stream responses rather than buffering everything in memory at once.

The verdict

Nano Banana 2 is the least-friction way to get production-grade image editing behind code, and OpenRouter removes the last piece of friction — the multi-vendor setup. One endpoint, one key, four model variants behind a one-field switch. For agents that need an image-editing tool, for pipelines that generate then refine, and for developers who want to compare Google’s editing against OpenAI’s without committing to either ecosystem, this is the cleanest starting point in the current lineup.

Start with google/gemini-3.1-flash-image as your default. Drop to -flash-lite-image for cost, step up to -pro-image for fidelity, and keep the original google/gemini-2.5-flash-image only if you are maintaining legacy code. Edit in small steps, state the change before the thing to preserve, and pin your provider only when you have a reason to.

Sources: OpenRouter blog tutorial, “Nano Banana API: Edit Images with Gemini in Code” (openrouter.ai); OpenRouter model page for Google Gemini 3.1 Flash Image (Nano Banana 2); OpenRouter model page for Gemini 3.1 Flash Image Preview.

Disclosure: CarCare Guide is reader-supported. When you buy through links on our site, we may earn an affiliate commission at no extra cost to you. Learn more.
A
Alex Chen