SPB Git

Repository Public

image-generation.md 104.0 KB 2,541 lines markdown

1> [!NOTE]2> **Note** : This version of the page covers the new [Interactions API](https://ai.google.dev/gemini-api/docs/interactions/interactions-overview), which is currently in Beta.  3> For stable production deployments, we recommend you continue to use the `generateContent` API. You can use the toggle on this page to switch between the versions.456# Nano Banana image generation78Prompt to prototype fully-functional, UI-complete apps, and see Nano Banana 2 integrated with real-world tools, data, and the Gemini ecosystem. All before writing a single line of code.910- Or build your own from prompts:11- ![magazine](https://storage.googleapis.com/generativeai-downloads/images/magazine-2.jpg) ![london](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/05-output.jpg) ![restore](https://storage.googleapis.com/generativeai-downloads/images/quetzal.png) ![banana](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/06-output.jpg) ![cafe](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/02-a-photo-of-an-everyday-scene-at-a-busy-cafe-servin.jpg) ![article](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/10-use-search-to-find-how-the-gemini-3-flash-launch-h.jpg) ![dog](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/01-an-icon-representing-a-cute-dog-the-background-is-.jpg) ![isometric](https://storage.googleapis.com/generativeai-downloads/images/isometric-pool.jpg)12- ![magazine](https://storage.googleapis.com/generativeai-downloads/images/magazine-2.jpg) Generated by Nano Banana 2 **Prompt:** "A photo of a glossy magazine cover, the minimal blue cover has the large bold words Nano Banana. The text is in a serif font and fills the view. No other text. In front of the text there is a portrait of a person in a sleek and minimal dress. She is playfully holding the number 2, which is the focal point.   13  Put the issue number and "Feb 2026" date in the corner along with a barcode. The magazine is on a shelf against an orange plastered wall, within a designer store."14- ![london](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/05-output.jpg) Generated by Nano Banana Pro **Prompt:** "Present a clear, 45° top-down isometric miniature 3D cartoon scene of London, featuring its most iconic landmarks and architectural elements. Use soft, refined textures with realistic PBR materials and gentle, lifelike lighting and shadows. Integrate the current weather conditions directly into the city environment to create an immersive atmospheric mood. Use a clean, minimalistic composition with a soft, solid-colored background. At the top-center, place the title "London" in large bold text, a prominent weather icon beneath it, then the date (small text) and temperature (medium text). All text must be centered with consistent spacing, and may subtly overlap the tops of the buildings."15- ![quetzal](https://storage.googleapis.com/generativeai-downloads/images/quetzal.png) Generated by Nano Banana 2 **Prompt:** "Use image search to find accurate images of a resplendent quetzal bird. Create a beautiful 3:2 wallpaper of this bird, with a natural top to bottom gradient and minimal composition."16- ![banana](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/06.jpg) Generated by Nano Banana Pro **Prompt:** "Put this logo on a high-end ad for a banana scented perfume. The logo is perfectly integrated into the bottle."17- ![cafe](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/02-a-photo-of-an-everyday-scene-at-a-busy-cafe-servin.jpg) Generated by Nano Banana Pro **Prompt:** "A photo of an everyday scene at a busy cafe serving breakfast. In the foreground is an anime man with blue hair, one of the people is a pencil sketch, another is a claymation person"18- ![article](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/10-use-search-to-find-how-the-gemini-3-flash-launch-h.jpg) Generated by Nano Banana Pro **Prompt:** "Use search to find how the Gemini 3 Flash launch has been received. Use this information to write a short article about it (with headings). Return a photo of the article as it appeared in a design focused glossy magazine. It is a photo of a single folded over page, showing the article about Gemini 3 Flash. One hero photo. Headline in serif."19- ![dog](https://storage.googleapis.com/generativeai-downloads/images/Nano%20Banana%20Pro%20outputs%20for%20docs/01-an-icon-representing-a-cute-dog-the-background-is-.jpg) Generated by Nano Banana Pro **Prompt:** "An icon representing a cute dog. The background is white. Make the icons in a colorful and tactile 3D style. No text."20- ![isometric](https://storage.googleapis.com/generativeai-downloads/images/isometric-pool.jpg) Generated by Nano Banana 2 **Prompt:** "Make a photo that is perfectly isometric. It is not a miniature, it is a captured photo that just happened to be perfectly isometric. It is a photo of a beautiful modern garden. There's a large 2 shaped pool and the words: Nano Banana 2."2122**Nano Banana** is the name for Gemini's native image generation capabilities.23Gemini can generate and process images conversationally24with text, images, or a combination of both. This lets you create, edit, and25iterate on visuals with unprecedented control.2627Nano Banana refers to two distinct models available in the Gemini API:2829- **Nano Banana 2** : The [Gemini 3.1 Flash Image](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-image) model (`gemini-3.1-flash-image`). This model serves as the high-efficiency counterpart to Gemini 3 Pro Image, optimized for speed and high-volume developer use cases.30- **Nano Banana Pro** : The [Gemini 3 Pro Image](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-image) model (`gemini-3-pro-image`). This model is designed for professional asset production, utilizing advanced reasoning ("Thinking") to follow complex instructions and render high-fidelity text.31- **Nano Banana** : The [Gemini 2.5 Flash Image](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image) model (`gemini-2.5-flash-image`). This model is designed for speed and efficiency, optimized for high-volume, low-latency tasks.3233All generated images include a [SynthID watermark](https://ai.google.dev/responsible/docs/safeguards/synthid).3435## Image generation (text-to-image)3637### Python3839    from google import genai40    from PIL import Image41    import base644243    client = genai.Client()4445    interaction = client.interactions.create(46        model="gemini-3.1-flash-image",47        input="Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",48    )4950    with open("generated_image.png", "wb") as f:5152        f.write(base64.b64decode(interaction.output_image.data))5354### JavaScript5556    import { GoogleGenAI } from "@google/genai";57    import * as fs from "node:fs";5859    async function main() {6061      const ai = new GoogleGenAI({});6263      const prompt =64        "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";6566      const interaction = await ai.interactions.create({67        model: "gemini-3.1-flash-image",68        input: prompt,69      });70      const generatedImage = interaction.output_image;71      if (generatedImage) {72        const buffer = Buffer.from(generatedImage.data, "base64");73        fs.writeFileSync("gemini-native-image.png", buffer);74        console.log("Image saved as gemini-native-image.png");75      }76    }7778    main();7980### REST8182    curl -s -X POST \83      "https://generativelanguage.googleapis.com/v1beta/interactions" \84      -H "x-goog-api-key: $GEMINI_API_KEY" \85      -H "Content-Type: application/json" \86      -H "Api-Revision: 2026-05-20" \87      -d '{88        "model": "gemini-3.1-flash-image",89        "input": [90          {"type": "text", "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}91        ]92      }'9394You can retrieve generated image data by using the `interaction.output_image`95property, which returns the last generated image block. For details on96convenience properties, see the97[Interactions overview](https://ai.google.dev/gemini-api/docs/interactions#convenience-properties).9899> [!NOTE]100> **Note:** For complex, interleaved text-and-image outputs (such as stories containing illustrations), convenience properties will not capture all parts. You must manually iterate over the steps instead---see [Interleaved text and images](https://ai.google.dev/gemini-api/docs/interactions/image-generation#interleaved-output) for an example.101102## Image editing (text-and-image-to-image)103104**Reminder** : Make sure you have the necessary rights to any images you upload.105Don't generate content that infringe on others' rights, including videos or106images that deceive, harass, or harm. Your use of this generative AI service is107subject to our [Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy).108109Provide an image and use text prompts to add, remove, or modify elements,110change the style, or adjust the color grading.111112The following example demonstrates uploading `base64` encoded images.113For multiple images, larger payloads, and supported MIME types, check the [Image114understanding](https://ai.google.dev/gemini-api/docs/interactions/image-understanding) page.115116### Python117118    from google import genai119    from PIL import Image120    import base64121122    client = genai.Client()123124    with open("/path/to/cat_image.png", "rb") as f:125        image_bytes = f.read()126127    interaction = client.interactions.create(128        model="gemini-3.1-flash-image",129        input=[130            {131              "type": "text",132              "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"133            },134            {135                "type": "image",136                "data": base64.b64encode(image_bytes).decode('utf-8'),137                "mime_type": "image/png"138            }139        ],140    )141142    with open("generated_image.png", "wb") as f:143144        f.write(base64.b64decode(interaction.output_image.data))145146### JavaScript147148    import { GoogleGenAI } from "@google/genai";149    import * as fs from "node:fs";150151    async function main() {152153      const ai = new GoogleGenAI({});154155      const imagePath = "path/to/cat_image.png";156      const imageData = fs.readFileSync(imagePath);157      const base64Image = imageData.toString("base64");158159      const prompt = [160        { type: "text", text: "Create a picture of my cat eating a nano-banana in a" +161                "fancy restaurant under the Gemini constellation" },162        {163          type: "image",164          mime_type: "image/png",165          data: base64Image166        },167      ];168169      const interaction = await ai.interactions.create({170        model: "gemini-3.1-flash-image",171        input: prompt,172      });173      const generatedImage = interaction.output_image;174      if (generatedImage) {175        const buffer = Buffer.from(generatedImage.data, "base64");176        fs.writeFileSync("gemini-native-image.png", buffer);177        console.log("Image saved as gemini-native-image.png");178      }179    }180181    main();182183### REST184185    curl -s -X POST \186      "https://generativelanguage.googleapis.com/v1beta/interactions" \187        -H "x-goog-api-key: $GEMINI_API_KEY" \188        -H 'Content-Type: application/json' \189        -H "Api-Revision: 2026-05-20" \190        -d "{191          \"model\": \"gemini-3.1-flash-image\",192          \"input\": [193            {\"type\": \"text\", \"text\": \"Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"},194            {195              \"type\": \"image\",196              \"mime_type\": \"image/jpeg\",197              \"data\": \"<BASE64_IMAGE_DATA>\"198            }199          ]200        }"201202### Multi-turn image editing203204Keep generating and editing images conversationally. Multi-turn205conversation is the recommended way to iterate on images. The following206example shows a prompt to generate an infographic about photosynthesis.207208### Python209210    from google import genai211    import base64212213    client = genai.Client()214215    interaction = client.interactions.create(216        model="gemini-3.1-flash-image",217        input="Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.",218        tools=[{"type": "google_search"}],219    )220221    with open("photosynthesis.png", "wb") as f:222223        f.write(base64.b64decode(interaction.output_image.data))224225### JavaScript226227    import { GoogleGenAI } from "@google/genai";228    import * as fs from "node:fs";229230    const ai = new GoogleGenAI({});231232    async function main() {233      const interaction = await ai.interactions.create({234        model: "gemini-3.1-flash-image",235        input: "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.",236        tools: [{"type": "google_search"}],237      });238239      const generatedImage = interaction.output_image;240      if (generatedImage) {241        const buffer = Buffer.from(generatedImage.data, "base64");242        fs.writeFileSync("photosynthesis.png", buffer);243        console.log("Image saved as photosynthesis.png");244      }245    }246247    await main();248249### REST250251    curl -s -X POST \252      "https://generativelanguage.googleapis.com/v1beta/interactions" \253      -H "x-goog-api-key: $GEMINI_API_KEY" \254      -H "Content-Type: application/json" \255      -H "Api-Revision: 2026-05-20" \256      -d '{257        "model": "gemini-3.1-flash-image",258        "input": [259          {"type": "text", "text": "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plants favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids cookbook, suitable for a 4th grader."}260        ],261        "tools": [{"type": "google_search"}]262      }'263264![AI-generated infographic about photosynthesis](https://ai.google.dev/static/gemini-api/docs/images/infographic-eng.png) AI-generated infographic about photosynthesis265266You can then use the `previous_interaction_id` to change the language on the graphic to Spanish.267268### Python269270    interaction_2 = client.interactions.create(271        model="gemini-3.1-flash-image",272        input="Update this infographic to be in Spanish. Do not change any other elements of the image.",273        previous_interaction_id=interaction.id,274        response_format={275            "type": "image",276            "mime_type": "image/jpeg",277            "aspect_ratio": "16:9",278            "image_size": "2K"279        },280    )281282    generated_image = interaction_2.output_image283    if generated_image:284        with open("photosynthesis_spanish.png", "wb") as f:285            f.write(base64.b64decode(generated_image.data))286287### JavaScript288289    const interaction2 = await ai.interactions.create({290      model: "gemini-3.1-flash-image",291      input: "Update this infographic to be in Spanish. Do not change any other elements of the image.",292      previous_interaction_id: interaction.id,293      response_format: {294        type: "image",295        mime_type: "image/png",296        aspect_ratio: "16:9",297        image_size: "2K"298      },299    });300301    const generatedImage = interaction2.output_image;302    if (generatedImage) {303      const buffer = Buffer.from(generatedImage.data, "base64");304      fs.writeFileSync("photosynthesis_spanish.png", buffer);305    }306307### REST308309    curl -s -X POST \310      "https://generativelanguage.googleapis.com/v1beta/interactions" \311      -H "x-goog-api-key: $GEMINI_API_KEY" \312      -H 'Content-Type: application/json' \313      -H "Api-Revision: 2026-05-20" \314      -d '{315        "model": "gemini-3.1-flash-image",316        "input": "Update this infographic to be in Spanish. Do not change any other elements of the image.",317        "previous_interaction_id": "<PREVIOUS_INTERACTION_ID>",318        "response_format": {319          "type": "image",320          "mime_type": "image/jpeg",321          "aspect_ratio": "16:9",322          "image_size": "2K"323        }324      }'325326![AI-generated infographic of photosynthesis in Spanish](https://ai.google.dev/static/gemini-api/docs/images/infographic-spanish.png) AI-generated infographic of photosynthesis in Spanish327328## New with Gemini 3 Image models329330Gemini 3 offers state-of-the-art image generation and editing models. Gemini 3.1331Flash Image is optimized for speed and high-volume use-cases, and Gemini 3332Pro Image is optimized for professional asset production.333Designed to tackle the most challenging workflows through advanced reasoning,334they excel at complex, multi-turn creation and modification tasks.335336- **High-resolution output** : Built-in generation capabilities for 1K, 2K, and 4K visuals.337  - **Gemini 3.1 Flash Image** adds the smaller 512px (0.5K) resolution.338- **Advanced text rendering**: Capable of generating legible, stylized text for infographics, menus, diagrams, and marketing assets.339- **Grounding with Google Search** : The model can use Google Search as a tool to verify facts and generate imagery based on real-time data (e.g., current weather maps, stock charts, recent events).340  - **Gemini 3.1 Flash Image** adds the integration of Google Image Search Grounding alongside Web Search.341- **Thinking mode**: The model utilizes a "thinking" process to reason through complex prompts. It generates interim "thought images" (visible in the backend but not charged) to refine the composition before producing the final high-quality output.342- **Up to 14 reference images**: You can now mix up to 14 reference images to produce the final image.343- **New aspect ratios** : Gemini 3.1 Flash Image adds 1:4, 4:1, 1:8, and 8:1 [aspect ratios](https://ai.google.dev/gemini-api/docs/interactions/image-generation#aspect_ratios_and_image_size).344345### Use up to 14 reference images346347Gemini 3 image models let you to mix up to 14 reference images. These 14 images348can include the following:349350| Gemini 3.1 Flash Image | Gemini 3 Pro Image |351|---|---|352| Up to 10 images of objects with high-fidelity to include in the final image | Up to 6 images of objects with high-fidelity to include in the final image |353| Up to 4 images of characters to maintain character consistency | Up to 5 images of characters to maintain character consistency |354| N/A | Up to 3 images to be used as style references |355356### Python357358    from google import genai359    from google.genai import types360    from PIL import Image361    import base64362363    prompt = "An office group photo of these people, they are making funny faces."364365    client = genai.Client()366367    interaction = client.interactions.create(368        model="gemini-3.1-flash-image",369        input=[370            {371                "type": "text",372                "text": prompt,373            },374            {375                "type": "image",376                "data": base64.b64encode(image_bytes).decode('utf-8'),377                "mime_type": "image/png"378            },379            {380                "type": "image",381                "data": base64.b64encode(image_bytes).decode('utf-8'),382                "mime_type": "image/png"383            },384            {385                "type": "image",386                "data": base64.b64encode(image_bytes).decode('utf-8'),387                "mime_type": "image/png"388            },389            {390                "type": "image",391                "data": base64.b64encode(image_bytes).decode('utf-8'),392                "mime_type": "image/png"393            },394            {395                "type": "image",396                "data": base64.b64encode(image_bytes).decode('utf-8'),397                "mime_type": "image/png"398            },399        ],400        response_format={401            "type": "image",402            "aspect_ratio": "5:4",403            "image_size": "2K"404        },405    )406407    with open("office.png", "wb") as f:408409        f.write(base64.b64decode(interaction.output_image.data))410411### JavaScript412413    import { GoogleGenAI } from "@google/genai";414    import * as fs from "node:fs";415416    async function main() {417      const ai = new GoogleGenAI({});418419      const input = [420        {421          type: "text",422          text: "An office group photo of these people, they are making funny faces.",423        },424        { type: "image", mime_type: "image/jpeg", data: base64ImageFile1 },425        { type: "image", mime_type: "image/jpeg", data: base64ImageFile2 },426        { type: "image", mime_type: "image/jpeg", data: base64ImageFile3 },427        { type: "image", mime_type: "image/jpeg", data: base64ImageFile4 },428        { type: "image", mime_type: "image/jpeg", data: base64ImageFile5 },429      ];430431      const interaction = await ai.interactions.create({432        model: "gemini-3.1-flash-image",433        input: input,434        response_format: {435          type: "image",436          aspect_ratio: "5:4",437          image_size: "2K",438        },439      });440441      const buffer = Buffer.from(interaction.output_image.data, 'base64');442443      fs.writeFileSync('office.png', buffer);444    }445446    main();447448### REST449450    curl -s -X POST \451      "https://generativelanguage.googleapis.com/v1beta/interactions" \452        -H "x-goog-api-key: $GEMINI_API_KEY" \453        -H 'Content-Type: application/json' \454        -H "Api-Revision: 2026-05-20" \455        -d "{456          \"model\": \"gemini-3.1-flash-image\",457          \"input\": [458            {\"type\": \"text\", \"text\": \"An office group photo of these people, they are making funny faces.\"},459            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_1>\"},460            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_2>\"},461            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_3>\"},462            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_4>\"},463            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_5>\"}464          ],465          \"response_format\": {466            \"type\": \"image\",467            \"aspect_ratio\": \"5:4\",468            \"image_size\": \"2K\"469          }470        }"471472![AI-generated office group photo](https://ai.google.dev/static/gemini-api/docs/images/office-group-photo.jpeg) AI-generated office group photo473474### Grounding with Google Search475476Use the [Google Search tool](https://ai.google.dev/gemini-api/docs/interactions/google-search) to generate images477based on real-time information, such as weather forecasts, stock charts, or478recent events.479480Note that when using Grounding with Google Search with image generation,481image-based search results are not passed to the generation model and are482excluded from the response (see [Grounding with Google Image Search](https://ai.google.dev/gemini-api/docs/interactions/image-generation#image-search))483484### Python485486    from google import genai487    from google.genai import types488    import base64489    prompt = "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day"490491    client = genai.Client()492493    interaction = client.interactions.create(494        model="gemini-3.1-flash-image",495        input=prompt,496        tools=[{"type": "google_search"}],497        response_format={498            "type": "image",499            "mime_type": "image/jpeg",500            "aspect_ratio": "16:9"501        },502    )503504    with open("weather.png", "wb") as f:505506        f.write(base64.b64decode(interaction.output_image.data))507508### JavaScript509510    import { GoogleGenAI } from "@google/genai";511    import * as fs from "node:fs";512513    async function main() {514      const ai = new GoogleGenAI({});515516      const interaction = await ai.interactions.create({517        model: "gemini-3.1-flash-image",518        input: "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day",519        tools: [{"type": "google_search"}],520        response_format: {521          type: "image",522          mime_type: "image/png",523          aspect_ratio: "16:9",524          image_size: "2K"525        },526      });527528      const buffer = Buffer.from(interaction.output_image.data, 'base64');529530      fs.writeFileSync('weather.png', buffer);531    }532533    main();534535### REST536537    curl -s -X POST \538      "https://generativelanguage.googleapis.com/v1beta/interactions" \539      -H "x-goog-api-key: $GEMINI_API_KEY" \540      -H "Content-Type: application/json" \541      -H "Api-Revision: 2026-05-20" \542      -d '{543        "model": "gemini-3.1-flash-image",544        "input": [545          {"type": "text", "text": "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day"}546        ],547        "tools": [{"type": "google_search"}],548        "response_format": {549          "type": "image",550          "mime_type": "image/jpeg",551          "aspect_ratio": "16:9"552        }553      }'554555![AI-generated five day weather chart for San Francisco](https://ai.google.dev/static/gemini-api/docs/images/weather-forecast.png) AI-generated five day weather chart for San Francisco556557The response includes `google_search_call` and `google_search_result` steps,558along with inline `url_citation` annotations on the text step:559560- **`google_search_result`** : Contains `search_suggestions`, an HTML snippet for rendering search suggestions in your UI.561- **`url_citation` annotations**: Inline citations on the text step linking parts of the response to their web sources.562563### Grounding with Google Search for Images (3.1 Flash)564565> [!NOTE]566> **Note:** This feature is only available for the Gemini 3.1 Flash Image model.567568Grounding with Google Image Search allows models to use web images retrieved via569Google Image Search as visual context for image generation. Image Search is a570new search type within the existing Grounding with Google Search tool,571functioning alongside standard [Web Search](https://ai.google.dev/gemini-api/docs/interactions/image-generation#use-with-grounding).572573To enable Image Search, configure the `google_search` tool in your API request574and specify `image_search` within the `search_types` array. Image Search can be575used independently or together with Web Search.576577### Python578579    from google import genai580581    client = genai.Client()582583    interaction = client.interactions.create(584        model="gemini-3.1-flash-image",585        input="A detailed painting of a Timareta butterfly resting on a flower",586        tools=[{587          "type": "google_search",588          "search_types": ["web_search", "image_search"]589        }]590    )591592### JavaScript593594    import { GoogleGenAI } from "@google/genai";595596    async function main() {597      const ai = new GoogleGenAI({});598599      const interaction = await ai.interactions.create({600        model: "gemini-3.1-flash-image",601        input: "A detailed painting of a Timareta butterfly resting on a flower",602        tools: [{603          "type": "google_search",604          "search_types": ["web_search", "image_search"]605        }]606      });607    }608609    main();610611### REST612613    curl -s -X POST \614      "https://generativelanguage.googleapis.com/v1beta/interactions" \615      -H "x-goog-api-key: $GEMINI_API_KEY" \616      -H "Content-Type: application/json" \617      -H "Api-Revision: 2026-05-20" \618      -d '{619        "model": "gemini-3.1-flash-image",620        "input": "A detailed painting of a Timareta butterfly resting on a flower",621        "tools": [{"type": "google_search", "search_types": ["web_search", "image_search"]}]622      }'623624**Display requirements**625626When you use Image Search within Grounding with Google Search, you must display627the `search_suggestions` from the `google_search_result` step. Full usage628requirements are detailed in the629[Terms of Service](https://ai.google.dev/gemini-api/terms#grounding-with-google-search).630631**Response**632633For grounded responses using image search, the API returns inline citations634and attribution metadata as part of the response steps:635636- **`url_citation` annotations** : Inline citations on the text content block637  within `model_output`, linking the generated content to its source.638639- **`google_search_result`** : Contains `search_suggestions`, an HTML640  snippet for rendering search suggestions in your UI.641642### Video-to-image generation (3.1 Flash)643644> [!NOTE]645> **Note:** This feature is only available for the Gemini 3.1 Flash Image model.646647Video-to-image generation allows you to generate new images using a video's context648as a multimodal reference. This is useful for creating high-quality video thumbnails, cinematic649posters, summary infographics, or new artwork inspired by a video scene.650651During generation, the model analyzes the video frames in context to extract visual themes652and key events, then uses them alongside your text prompt to synthesize the output image.653654You can pass public [YouTube URLs](https://ai.google.dev/gemini-api/docs/video-understanding#youtube)655directly in your API request or upload local video files using the656[Files API](https://ai.google.dev/gemini-api/docs/interactions/files).657658### Python659660    from google import genai661    from google.genai import types662    import base64663664    client = genai.Client()665666    interaction = client.interactions.create(667        model="gemini-3.1-flash-image",668        input=[669            {670                "type": "video",671                "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",672                "mime_type": "video/mp4"673            },674            {"type": "text", "text": "Generate a poster image that captures the key themes of this video."}675        ],676        response_format={"type": "image", "aspect_ratio": "16:9"}677    )678679    # Save the generated image part680    for step in interaction.steps:681        if step.type == "model_output":682            for content_block in step.content:683                if content_block.type == "text":684                    print(content_block.text)685                elif content_block.type == "image":686                    with open("video_poster.png", "wb") as f:687                        f.write(base64.b64decode(content_block.data))688                    print("Image saved as video_poster.png")689690### JavaScript691692    import { GoogleGenAI } from "@google/genai";693    import * as fs from "node:fs";694695    async function main() {696      const ai = new GoogleGenAI({});697698      const interaction = await ai.interactions.create({699        model: "gemini-3.1-flash-image",700        input: [701          {702            type: "video",703            uri: "https://www.youtube.com/watch?v=UTdfxFyOQTI",704            mime_type: "video/mp4"705          },706          { type: "text", text: "Generate a poster image that captures the key themes of this video." }707        ],708        response_format: {709          type: "image",710          aspect_ratio: "16:9"711        }712      });713714      for (const step of interaction.steps) {715        if (step.type === "model_output") {716          for (const contentBlock of step.content) {717            if (contentBlock.type === "text") {718              console.log(contentBlock.text);719            } else if (contentBlock.type === "image") {720              const buffer = Buffer.from(contentBlock.data, "base64");721              fs.writeFileSync("video_poster.png", buffer);722              console.log("Image saved as video_poster.png");723            }724          }725        }726      }727    }728729    main();730731### REST732733    curl -s -X POST \734      "https://generativelanguage.googleapis.com/v1beta/interactions" \735      -H "x-goog-api-key: $GEMINI_API_KEY" \736      -H 'Content-Type: application/json' \737      -H "Api-Revision: 2026-05-20" \738      -d '{739        "model": "gemini-3.1-flash-image",740        "input": [741          {742            "type": "video",743            "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",744            "mime_type": "video/mp4"745          },746          {747            "type": "text",748            "text": "Generate a poster image that captures the key themes of this video."749          }750        ],751        "response_format": {752          "type": "image",753          "aspect_ratio": "16:9"754        }755      }'756757![AI-generated infographic from a youtube video](https://ai.google.dev/static/gemini-api/docs/images/youtube_infographics.png) AI-generated infographic from a youtube video758759### Generate images up to 4K resolution760761Gemini 3 image models generate 1K images by default but can also output 2K,7624K, and 512px (05.K) (Gemini 3.1 Flash Image only) images. To generate higher763resolution assets, specify the `image_size` in the `response_format`.764765You must use an uppercase 'K' (e.g. 512px (05.K), 1K, 2K, 4K). Lowercase766parameters (e.g., 1k) will be rejected.767768### Python769770    from google import genai771    from google.genai import types772    import base64773774    prompt = "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English."775776    client = genai.Client()777778    interaction = client.interactions.create(779        model="gemini-3.1-flash-image",780        input=prompt,781        response_format={782            "type": "image",783            "mime_type": "image/jpeg",784            "aspect_ratio": "1:1",785            "image_size": "1K"786        },787    )788789    print(interaction.output_text)790791    with open("butterfly.png", "wb") as f:792793        f.write(base64.b64decode(interaction.output_image.data))794795### JavaScript796797    import { GoogleGenAI } from "@google/genai";798    import * as fs from "node:fs";799800    async function main() {801      const ai = new GoogleGenAI({});802803      const interaction = await ai.interactions.create({804        model: "gemini-3.1-flash-image",805        input: "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.",806        response_format: {807          type: "image",808          mime_type: "image/png",809          aspect_ratio: "1:1",810          image_size: "1K",811        },812      });813814      console.log(interaction.output_text);815816      const buffer = Buffer.from(interaction.output_image.data, 'base64');817818      fs.writeFileSync('butterfly.png', buffer);819    }820821    main();822823### REST824825    curl -s -X POST \826      "https://generativelanguage.googleapis.com/v1beta/interactions" \827      -H "x-goog-api-key: $GEMINI_API_KEY" \828      -H "Content-Type: application/json" \829      -H "Api-Revision: 2026-05-20" \830      -d '{831        "model": "gemini-3.1-flash-image",832        "input": "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.",833        "response_format": {834          "type": "image",835          "mime_type": "image/jpeg",836          "aspect_ratio": "1:1",837          "image_size": "1K"838        }839      }'840841The following is an example image generated from this prompt:842![AI-generated Da Vinci style anatomical sketch of a dissected Monarch butterfly.](https://ai.google.dev/static/gemini-api/docs/images/gemini3-4k-image.png) AI-generated Da Vinci style anatomical sketch of a dissected Monarch butterfly.843844### Thinking Process845846Gemini 3 image models are thinking models that use a reasoning847process ("Thinking") for complex prompts. This feature is enabled by default and848cannot be disabled in the API. To learn more about the thinking process, see849the [Gemini Thinking](https://ai.google.dev/gemini-api/docs/interactions/thinking) guide.850851The model generates up to two interim images to test composition and logic. The852last image within Thinking is also the final rendered image.853854You can check the thoughts that lead to the final image being produced.855856### Python857858    for step in interaction.steps:859        if step.type == "thought":860            for content_block in step.summary:861                if content_block.type == "text":862                    print(content_block.text)863                elif content_block.type == "image":864                    image = Image.open(io.BytesIO(base64.b64decode(content_block.data)))865                    image.show()866867### JavaScript868869    for (const step of interaction.steps) {870      if (step.type === "thought") {871        for (const contentBlock of step.summary) {872          if (contentBlock.type === "text") {873            console.log(contentBlock.text);874          } else if (contentBlock.type === "image") {875            const buffer = Buffer.from(contentBlock.data, 'base64');876            fs.writeFileSync('thought_image.png', buffer);877          }878        }879      }880    }881882#### Interleaved text and images883884While standard image generation models only output images, some advanced Gemini8853 models (such as `gemini-3-pro-image`) can generate interleaved886content---like stories or instructional guides containing both text blocks and887illustrations inside the same response.888889Because the output is complex and interleaved, convenience properties like890`.output_image` or `.output_text` will not capture the full sequence. To access891and save interleaved content, you must manually iterate over `steps`:892893### Python894895    interaction = client.interactions.create(896        model="gemini-3-pro-image",897        input="Write the story of the lifecycle of a monarch butterfly, interleave illustrations",898    )899900    image_counter = 1901    for step in interaction.steps:902        if step.type == "model_output":903            for content_block in step.content:904                if content_block.type == "text":905                    print(content_block.text)906                elif content_block.type == "image":907                    filename = f"butterfly_lifecycle_{image_counter}.png"908                    with open(filename, "wb") as f:909                        f.write(base64.b64decode(content_block.data))910                    print(f"\n[Saved illustration: {filename}]\n")911                    image_counter += 1912913### JavaScript914915    const interaction = await ai.interactions.create({916        model: "gemini-3-pro-image",917        input: "Write the story of the lifecycle of a monarch butterfly, interleave illustrations",918    });919920    let imageCounter = 1;921    for (const step of interaction.steps) {922      if (step.type === "model_output") {923        for (const contentBlock of step.content) {924          if (contentBlock.type === "text") {925            console.log(contentBlock.text);926          } else if (contentBlock.type === "image") {927            const buffer = Buffer.from(contentBlock.data, "base64");928            const filename = `butterfly_lifecycle_${imageCounter}.png`;929            fs.writeFileSync(filename, buffer);930            console.log(`\n[Saved illustration: ${filename}]\n`);931            imageCounter++;932          }933        }934      }935    }936937#### Controlling thinking levels938939With Gemini 3.1 Flash Image, you can control the amount of thinking the model940uses to balance quality and latency. The default `thinking_level` is `minimal`,941and the supported levels are `minimal` and `high`.942943### Python944945    from google import genai946    from PIL import Image947    import base64948    import io949950    client = genai.Client()951952    interaction = client.interactions.create(953        model="gemini-3.1-flash-image",954        input="A futuristic city built inside a giant glass bottle floating in space",955        generation_config={"thinking_level": "high"},956    )957958    print(interaction.output_text)959960    image = Image.open(io.BytesIO(base64.b64decode(interaction.output_image.data)))961962    image.show()963964### JavaScript965966    import { GoogleGenAI } from "@google/genai";967    import * as fs from "node:fs";968969    async function main() {970      const ai = new GoogleGenAI({});971972      const interaction = await ai.interactions.create({973        model: "gemini-3.1-flash-image",974        input: "A futuristic city built inside a giant glass bottle floating in space",975        generation_config: { thinking_level: "high" },976      });977978      console.log(interaction.output_text);979980      const buffer = Buffer.from(interaction.output_image.data, 'base64');981982      fs.writeFileSync('image.png', buffer);983    }984    main();985986### REST987988    curl -s -X POST \989      "https://generativelanguage.googleapis.com/v1beta/interactions" \990      -H "x-goog-api-key: $GEMINI_API_KEY" \991      -H "Content-Type: application/json" \992      -H "Api-Revision: 2026-05-20" \993      -d '{994        "model": "gemini-3.1-flash-image",995        "input": "A futuristic city built inside a giant glass bottle floating in space",996        "generation_config": {997          "thinking_level": "high"998        }999      }'10001001Note that thinking tokens are billed by default for thinking models, as the1002[thinking process](https://ai.google.dev/gemini-api/docs/interactions/image-generation#thinking-process) always happens by default whether you view1003the process or not.10041005## Other image generation modes10061007Although Nano Banana image generation models are recommended for most use cases,1008you can also explore dedicated image generation models:10091010- **[Imagen](https://ai.google.dev/gemini-api/docs/imagen)**: Google's text-to-image models optimized for generating high-quality images.1011- **[Veo](https://ai.google.dev/gemini-api/docs/video)**: Google's video generation model.10121013## Generate images in batch10141015All of the image generation capabilities described on this page can also be1016run as batch jobs using the [Batch API](https://ai.google.dev/gemini-api/docs/batch).10171018## Prompting guide and strategies10191020This section provides prompt examples and templates for common image generation1021and editing workflows. Each example includes a re-usable template and a1022sample prompt for the Interactions API.10231024### Prompts for generating images10251026The following examples show how to use text prompts to generate various types of1027images.10281029#### 1. Photorealistic scenes10301031Describe a scene in rich detail. The more specific you are, the more control you1032have over the results.10331034### Template10351036    A photorealistic [type of shot] of a [subject description] in a [setting1037    description]. [Description of the light]. Shot from a [camera angle]1038    with a [lens type].10391040### Prompt10411042    A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.10431044### Python10451046    from google import genai1047    from google.genai import types1048    import base6410491050    client = genai.Client()10511052    interaction = client.interactions.create(1053        model="gemini-3.1-flash-image",1054        input="A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",1055        response_format=[1056            {1057                "type": "image",1058                "mime_type": "image/jpeg",1059                "aspect_ratio": "16:9",1060            }1061        ],1062    )10631064    print(interaction.output_text)10651066    with open("coral_reef.png", "wb") as f:10671068        f.write(base64.b64decode(interaction.output_image.data))10691070### JavaScript10711072    import { GoogleGenAI } from "@google/genai";1073    import * as fs from "node:fs";10741075    async function main() {1076      const ai = new GoogleGenAI({});10771078      const interaction = await ai.interactions.create({1079        model: "gemini-3.1-flash-image",1080        input: "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",1081        response_format: [1082          {1083            type: "image",1084            mime_type: "image/jpeg",1085            aspect_ratio: "16:9",1086          }1087        ],1088      });1089      console.log(interaction.output_text);10901091      const buffer = Buffer.from(interaction.output_image.data, 'base64');10921093      fs.writeFileSync('coral_reef.png', buffer);1094    }10951096    main();10971098### REST10991100    curl -s -X POST \1101      "https://generativelanguage.googleapis.com/v1beta/interactions" \1102      -H "x-goog-api-key: $GEMINI_API_KEY" \1103      -H "Content-Type: application/json" \1104      -H "Api-Revision: 2026-05-20" \1105      -d '{1106        "model": "gemini-3.1-flash-image",1107        "input": "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",1108        "response_format": {1109          "type": "image",1110          "mime_type": "image/png",1111          "aspect_ratio": "16:9"1112        }1113      }'11141115![A photorealistic wide-angle shot of a vibrant coral reef...](https://ai.google.dev/static/gemini-api/docs/images/coral_reef.png) A photorealistic wide-angle shot of a vibrant coral reef...11161117#### 2. Stylized illustrations \& stickers11181119Describe the artistic style, subject, and medium. Be specific about the visual1120detail (bold lines, colors, etc.) for consistent results.11211122### Template11231124    A [style] of a [subject, with details about accessories or actions]1125    doing [activity]. The design features [visual qualities, e.g., bold outlines,1126    cel-shading, etc.] and [color/background preference].11271128### Prompt11291130    A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.11311132### Python11331134    from google import genai1135    import base6411361137    client = genai.Client()11381139    interaction = client.interactions.create(1140        model="gemini-3.1-flash-image",1141        input="A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.",1142    )11431144    for step in interaction.steps:1145        if step.type == "model_output":1146            for content_block in step.content:1147                if content_block.type == "text":1148                    print(content_block.text)1149                elif content_block.type == "image":1150                    with open("red_panda_sticker.png", "wb") as f:1151                        f.write(base64.b64decode(content_block.data))11521153### JavaScript11541155    import { GoogleGenAI } from "@google/genai";1156    import * as fs from "node:fs";11571158    async function main() {1159      const ai = new GoogleGenAI({});11601161      const interaction = await ai.interactions.create({1162        model: "gemini-3.1-flash-image",1163        input: "A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.",1164      });1165      for (const step of interaction.steps) {1166        if (step.type === "model_output") {1167          for (const contentBlock of step.content) {1168            if (contentBlock.type === "text") {1169              console.log(contentBlock.text);1170            } else if (contentBlock.type === "image") {1171              const buffer = Buffer.from(contentBlock.data, "base64");1172              fs.writeFileSync("red_panda_sticker.png", buffer);1173            }1174          }1175        }1176      }1177    }11781179    main();11801181### REST11821183    curl -s -X POST \1184      "https://generativelanguage.googleapis.com/v1beta/interactions" \1185      -H "x-goog-api-key: $GEMINI_API_KEY" \1186      -H "Content-Type: application/json" \1187      -d '{1188        "model": "gemini-3.1-flash-image",1189        "input": "A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It is munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white."1190      }'11911192![A kawaii-style sticker of a happy red...](https://ai.google.dev/static/gemini-api/docs/images/red_panda_sticker.png) A kawaii-style sticker of a happy red panda...11931194#### 3. Accurate text in images11951196Gemini excels at rendering text. Be clear about the text, the font style1197(descriptively), and the overall design. Use Gemini 3 Pro Image for1198professional asset production.11991200### Template12011202    Create a [image type] for [brand/concept] with the text "[text to render]"1203    in a [font style]. The design should be [style description], with a1204    [color scheme].12051206### Prompt12071208    Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.12091210### Python12111212    from google import genai1213    import base6412141215    client = genai.Client()12161217    interaction = client.interactions.create(1218        model="gemini-3.1-flash-image",1219        input="Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",1220        response_format={"type": "image", "aspect_ratio": "1:1"},1221    )12221223    for step in interaction.steps:1224        if step.type == "model_output":1225            for content_block in step.content:1226                if content_block.type == "text":1227                    print(content_block.text)1228                elif content_block.type == "image":1229                    with open("logo_example.jpg", "wb") as f:1230                        f.write(base64.b64decode(content_block.data))12311232### JavaScript12331234    import { GoogleGenAI } from "@google/genai";1235    import * as fs from "node:fs";12361237    async function main() {1238      const ai = new GoogleGenAI({});12391240      const interaction = await ai.interactions.create({1241        model: "gemini-3.1-flash-image",1242        input: "Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",1243        response_format: { type: "image", aspect_ratio: "1:1" },1244      });1245      for (const step of interaction.steps) {1246        if (step.type === "model_output") {1247          for (const contentBlock of step.content) {1248            if (contentBlock.type === "text") {1249              console.log(contentBlock.text);1250            } else if (contentBlock.type === "image") {1251              const buffer = Buffer.from(contentBlock.data, "base64");1252              fs.writeFileSync("logo_example.jpg", buffer);1253            }1254          }1255        }1256      }1257    }12581259    main();12601261### REST12621263    curl -s -X POST \1264      "https://generativelanguage.googleapis.com/v1beta/interactions" \1265      -H "x-goog-api-key: $GEMINI_API_KEY" \1266      -H "Content-Type: application/json" \1267      -d '{1268        "model": "gemini-3.1-flash-image",1269        "input": "Create a modern, minimalist logo for a coffee shop called The Daily Grind. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",1270        "response_format": {1271          "type": "image",1272          "aspect_ratio": "1:1"1273        }1274      }'12751276![Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'...](https://ai.google.dev/static/gemini-api/docs/images/logo_example.jpg) Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'...12771278#### 4. Product mockups \& commercial photography12791280Perfect for creating clean, professional product shots for ecommerce,1281advertising, or branding.12821283### Template12841285    A high-resolution, studio-lit product photograph of a [product description]1286    on a [background surface/description]. The lighting is a [lighting setup,1287    e.g., three-point softbox setup] to [lighting purpose]. The camera angle is1288    a [angle type] to showcase [specific feature]. Ultra-realistic, with sharp1289    focus on [key detail]. [Aspect ratio].12901291### Prompt12921293    A high-resolution, studio-lit product photograph of a minimalist ceramic1294    coffee mug in matte black, presented on a polished concrete surface. The1295    lighting is a three-point softbox setup designed to create soft, diffused1296    highlights and eliminate harsh shadows. The camera angle is a slightly1297    elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with1298    sharp focus on the steam rising from the coffee. Square image.12991300### Python13011302    from google import genai1303    import base6413041305    client = genai.Client()13061307    interaction = client.interactions.create(1308        model="gemini-3.1-flash-image",1309        input="A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.",1310    )13111312    for step in interaction.steps:1313        if step.type == "model_output":1314            for content_block in step.content:1315                if content_block.type == "text":1316                    print(content_block.text)1317                elif content_block.type == "image":1318                    with open("product_mockup.png", "wb") as f:1319                        f.write(base64.b64decode(content_block.data))13201321### JavaScript13221323    import { GoogleGenAI } from "@google/genai";1324    import * as fs from "node:fs";13251326    async function main() {1327      const ai = new GoogleGenAI({});13281329      const interaction = await ai.interactions.create({1330        model: "gemini-3.1-flash-image",1331        input: "A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.",1332      });1333      for (const step of interaction.steps) {1334        if (step.type === "model_output") {1335          for (const contentBlock of step.content) {1336            if (contentBlock.type === "text") {1337              console.log(contentBlock.text);1338            } else if (contentBlock.type === "image") {1339              const buffer = Buffer.from(contentBlock.data, "base64");1340              fs.writeFileSync("product_mockup.png", buffer);1341            }1342          }1343        }1344      }1345    }13461347    main();13481349### REST13501351    curl -s -X POST \1352      "https://generativelanguage.googleapis.com/v1beta/interactions" \1353      -H "x-goog-api-key: $GEMINI_API_KEY" \1354      -H "Content-Type: application/json" \1355      -d '{1356        "model": "gemini-3.1-flash-image",1357        "input": "A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image."1358      }'13591360![A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug...](https://ai.google.dev/static/gemini-api/docs/images/product_mockup.png) A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug...13611362#### 5. Minimalist \& negative space design13631364Excellent for creating backgrounds for websites, presentations, or marketing1365materials where text will be overlaid.13661367### Template13681369    A minimalist composition featuring a single [subject] positioned in the1370    [bottom-right/top-left/etc.] of the frame. The background is a vast, empty1371    [color] canvas, creating significant negative space. Soft, subtle lighting.1372    [Aspect ratio].13731374### Prompt13751376    A minimalist composition featuring a single, delicate red maple leaf1377    positioned in the bottom-right of the frame. The background is a vast, empty1378    off-white canvas, creating significant negative space for text. Soft,1379    diffused lighting from the top left. Square image.13801381### Python13821383    from google import genai1384    import base6413851386    client = genai.Client()13871388    interaction = client.interactions.create(1389        model="gemini-3.1-flash-image",1390        input="A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.",1391    )13921393    for step in interaction.steps:1394        if step.type == "model_output":1395            for content_block in step.content:1396                if content_block.type == "text":1397                    print(content_block.text)1398                elif content_block.type == "image":1399                    with open("minimalist_design.png", "wb") as f:1400                        f.write(base64.b64decode(content_block.data))14011402### JavaScript14031404    import { GoogleGenAI } from "@google/genai";1405    import * as fs from "node:fs";14061407    async function main() {1408      const ai = new GoogleGenAI({});14091410      const interaction = await ai.interactions.create({1411        model: "gemini-3.1-flash-image",1412        input: "A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.",1413      });1414      for (const step of interaction.steps) {1415        if (step.type === "model_output") {1416          for (const contentBlock of step.content) {1417            if (contentBlock.type === "text") {1418              console.log(contentBlock.text);1419            } else if (contentBlock.type === "image") {1420              const buffer = Buffer.from(contentBlock.data, "base64");1421              fs.writeFileSync("minimalist_design.png", buffer);1422            }1423          }1424        }1425      }1426    }14271428    main();14291430### REST14311432    curl -s -X POST \1433      "https://generativelanguage.googleapis.com/v1beta/interactions" \1434      -H "x-goog-api-key: $GEMINI_API_KEY" \1435      -H "Content-Type: application/json" \1436      -d '{1437        "model": "gemini-3.1-flash-image",1438        "input": "A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image."1439      }'14401441![A minimalist composition featuring a single, delicate red maple leaf...](https://ai.google.dev/static/gemini-api/docs/images/minimalist_design.png) A minimalist composition featuring a single, delicate red maple leaf...14421443#### 6. Sequential art (Comic panel / Storyboard)14441445Builds on character consistency and scene description to create panels for1446visual storytelling. For accuracy with text and storytelling ability, these1447prompts work best with Gemini 3 Pro and Gemini 3.1 Flash Image.14481449### Template14501451    Make a 3 panel comic in a [style]. Put the character in a [type of scene].14521453### Prompt14541455    Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene.14561457### Python14581459    from google import genai1460    from PIL import Image1461    import base6414621463    client = genai.Client()14641465    with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:1466        image_bytes = f.read()1467    text_input = "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene."14681469    interaction = client.interactions.create(1470        model="gemini-3.1-flash-image",1471        input=[1472            {"type": "text", "text": text_input},1473            {1474                "type": "image",1475                "data": base64.b64encode(image_bytes).decode('utf-8'),1476                "mime_type": "image/jpeg"1477            }1478        ],1479    )14801481    for step in interaction.steps:1482        if step.type == "model_output":1483            for content_block in step.content:1484                if content_block.type == "text":1485                    print(content_block.text)1486                elif content_block.type == "image":1487                    with open("comic_panel.jpg", "wb") as f:1488                        f.write(base64.b64decode(content_block.data))14891490### JavaScript14911492    import { GoogleGenAI } from "@google/genai";1493    import * as fs from "node:fs";14941495    async function main() {1496      const ai = new GoogleGenAI({});14971498      const imagePath = "/path/to/your/man_in_white_glasses.jpg";1499      const imageData = fs.readFileSync(imagePath);1500      const base64Image = imageData.toString("base64");15011502      const input = [1503        { type: "text", text: "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene." },1504        {1505          type: "image",1506          mime_type: "image/jpeg",1507          data: base64Image1508        },1509      ];15101511      const interaction = await ai.interactions.create({1512        model: "gemini-3.1-flash-image",1513        input: input,1514      });1515      for (const step of interaction.steps) {1516        if (step.type === "model_output") {1517          for (const contentBlock of step.content) {1518            if (contentBlock.type === "text") {1519              console.log(contentBlock.text);1520            } else if (contentBlock.type === "image") {1521              const buffer = Buffer.from(contentBlock.data, "base64");1522              fs.writeFileSync("comic_panel.jpg", buffer);1523            }1524          }1525        }1526      }1527    }15281529    main();15301531### REST15321533    curl -s -X POST \1534      "https://generativelanguage.googleapis.com/v1beta/interactions" \1535      -H "x-goog-api-key: $GEMINI_API_KEY" \1536      -H "Content-Type: application/json" \1537      -d '{1538        "model": "gemini-3.1-flash-image",1539        "input": [1540          {"type": "text", "text": "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene."},1541          {"type": "image", "data": "<BASE64_IMAGE_DATA>", "mime_type": "image/jpeg"}1542        ]1543      }'15441545|---|---|1546| Input | Output |1547| ![Man in white glasses](https://ai.google.dev/static/gemini-api/docs/images/man_in_white_glasses.jpg) Input image | ![Make a 3 panel comic in a gritty, noir art style...](https://ai.google.dev/static/gemini-api/docs/images/comic_panel.jpg) Make a 3 panel comic in a gritty, noir art style... |15481549#### 7. Grounding with Google Search15501551Use Google Search to generate images based on recent or real-time information.1552This is useful for news, weather, and other time-sensitive topics.15531554### Prompt15551556    Make a simple but stylish graphic of last night's Arsenal game in the Champion's League15571558### Python15591560    from google import genai1561    from google.genai import types1562    import base6415631564    client = genai.Client()15651566    interaction = client.interactions.create(1567        model="gemini-3.1-flash-image",1568        input="Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",1569        tools=[{"type": "google_search"}],1570        response_format={"type": "image", "aspect_ratio": "16:9"},1571    )15721573    for step in interaction.steps:1574        if step.type == "model_output":1575            for content_block in step.content:1576                if content_block.type == "text":1577                    print(content_block.text)1578                elif content_block.type == "image":1579                    with open("football-score.jpg", "wb") as f:1580                        f.write(base64.b64decode(content_block.data))15811582### JavaScript15831584    import { GoogleGenAI } from "@google/genai";1585    import * as fs from "node:fs";15861587    async function main() {1588      const ai = new GoogleGenAI({});15891590      const interaction = await ai.interactions.create({1591        model: "gemini-3.1-flash-image",1592        input: "Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",1593        tools: [{ type: "google_search" }],1594        response_format: { type: "image", aspect_ratio: "16:9", image_size: "2K" },1595      });15961597      for (const step of interaction.steps) {1598        if (step.type === "model_output") {1599          for (const contentBlock of step.content) {1600            if (contentBlock.type === "text") {1601              console.log(contentBlock.text);1602            } else if (contentBlock.type === "image") {1603              const buffer = Buffer.from(contentBlock.data, "base64");1604              fs.writeFileSync("football-score.jpg", buffer);1605            }1606          }1607        }1608      }1609    }16101611    main();16121613### REST16141615    curl -s -X POST \1616      "https://generativelanguage.googleapis.com/v1beta/interactions" \1617      -H "x-goog-api-key: $GEMINI_API_KEY" \1618      -H "Content-Type: application/json" \1619      -d '{1620        "model": "gemini-3.1-flash-image",1621        "input": "Make a simple but stylish graphic of last nights Arsenal game in the Champions League",1622        "tools": [{"type": "google_search"}],1623        "response_format": {1624          "type": "image",1625          "aspect_ratio": "16:9"1626        }1627      }'16281629![AI-generated graphic of an Arsenal football score](https://ai.google.dev/static/gemini-api/docs/images/football-score.jpg) AI-generated graphic of an Arsenal football score16301631### Prompts for editing images16321633These examples show how to provide images alongside your text prompts for1634editing, composition, and style transfer.16351636#### 1. Adding and removing elements16371638Provide an image and describe your change. The model will match the original1639image's style, lighting, and perspective.16401641### Template16421643    Using the provided image of [subject], please [add/remove/modify] [element]1644    to/from the scene. Ensure the change is [description of how the change should1645    integrate].16461647### Prompt16481649    "Using the provided image of my cat, please add a small, knitted wizard hat1650    on its head. Make it look like it's sitting comfortably and matches the soft1651    lighting of the photo."16521653### Python16541655    from google import genai1656    from PIL import Image1657    import base6416581659    client = genai.Client()16601661    with open('/path/to/your/cat_photo.png', 'rb') as f:1662        image_bytes = f.read()1663    text_input = """Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off."""16641665    interaction = client.interactions.create(1666        model="gemini-3.1-flash-image",1667        input=[1668            {"type": "text", "text": text_input},1669            {1670                "type": "image",1671                "data": base64.b64encode(image_bytes).decode('utf-8'),1672                "mime_type": "image/png"1673            }1674        ],1675    )16761677    for step in interaction.steps:1678        if step.type == "model_output":1679            for content_block in step.content:1680                if content_block.type == "text":1681                    print(content_block.text)1682                elif content_block.type == "image":1683                    with open("cat_with_hat.png", "wb") as f:1684                        f.write(base64.b64decode(content_block.data))16851686### JavaScript16871688    import { GoogleGenAI } from "@google/genai";1689    import * as fs from "node:fs";16901691    async function main() {1692      const ai = new GoogleGenAI({});16931694      const imagePath = "/path/to/your/cat_photo.png";1695      const imageData = fs.readFileSync(imagePath);1696      const base64Image = imageData.toString("base64");16971698      const input = [1699        { type: "text", text: "Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off." },1700        {1701          type: "image",1702          mime_type: "image/png",1703          data: base64Image1704        },1705      ];17061707      const interaction = await ai.interactions.create({1708        model: "gemini-3.1-flash-image",1709        input: input,1710      });1711      for (const step of interaction.steps) {1712        if (step.type === "model_output") {1713          for (const contentBlock of step.content) {1714            if (contentBlock.type === "text") {1715              console.log(contentBlock.text);1716            } else if (contentBlock.type === "image") {1717              const buffer = Buffer.from(contentBlock.data, "base64");1718              fs.writeFileSync("cat_with_hat.png", buffer);1719            }1720          }1721        }1722      }1723    }17241725    main();17261727### REST17281729    curl -s -X POST \1730      "https://generativelanguage.googleapis.com/v1beta/interactions" \1731        -H "x-goog-api-key: $GEMINI_API_KEY" \1732        -H 'Content-Type: application/json' \1733        -d "{1734          \"model\": \"gemini-3.1-flash-image\",1735          \"input\": [1736                {\"type\": \"text\", \"text\": \"Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off.\"},1737                {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"}1738            ]1739        }"17401741|---|---|1742| Input | Output |1743| :cat: A photorealistic picture of a fluffy ginger cat... | ![Using the provided image of my cat, please add a small, knitted wizard hat...](https://ai.google.dev/static/gemini-api/docs/images/cat_with_hat.png) Using the provided image of my cat, please add a small, knitted wizard hat... |17441745#### 2. Inpainting (Semantic masking)17461747Conversationally define a "mask" to edit a specific part of an image while1748leaving the rest untouched.17491750### Template17511752    Using the provided image, change only the [specific element] to [new1753    element/description]. Keep everything else in the image exactly the same,1754    preserving the original style, lighting, and composition.17551756### Prompt17571758    "Using the provided image of a living room, change only the blue sofa to be1759    a vintage, brown leather chesterfield sofa. Keep the rest of the room,1760    including the pillows on the sofa and the lighting, unchanged."17611762### Python17631764    from google import genai1765    from PIL import Image1766    import base6417671768    client = genai.Client()17691770    with open('/path/to/your/living_room.png', 'rb') as f:1771        image_bytes = f.read()1772    text_input = """Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged."""17731774    interaction = client.interactions.create(1775        model="gemini-3.1-flash-image",1776        input=[1777            {1778                "type": "image",1779                "data": base64.b64encode(image_bytes).decode('utf-8'),1780                "mime_type": "image/png"1781            },1782            {"type": "text", "text": text_input}1783        ],1784    )17851786    for step in interaction.steps:1787        if step.type == "model_output":1788            for content_block in step.content:1789                if content_block.type == "text":1790                    print(content_block.text)1791                elif content_block.type == "image":1792                    with open("living_room_edited.png", "wb") as f:1793                        f.write(base64.b64decode(content_block.data))17941795### JavaScript17961797    import { GoogleGenAI } from "@google/genai";1798    import * as fs from "node:fs";17991800    async function main() {1801      const ai = new GoogleGenAI({});18021803      const imagePath = "/path/to/your/living_room.png";1804      const imageData = fs.readFileSync(imagePath);1805      const base64Image = imageData.toString("base64");18061807      const input = [1808        {1809          type: "image",1810          mime_type: "image/png",1811          data: base64Image1812        },1813        { type: "text", text: "Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged." },1814      ];18151816      const interaction = await ai.interactions.create({1817        model: "gemini-3.1-flash-image",1818        input: input,1819      });1820      for (const step of interaction.steps) {1821        if (step.type === "model_output") {1822          for (const contentBlock of step.content) {1823            if (contentBlock.type === "text") {1824              console.log(contentBlock.text);1825            } else if (contentBlock.type === "image") {1826              const buffer = Buffer.from(contentBlock.data, "base64");1827              fs.writeFileSync("living_room_edited.png", buffer);1828            }1829          }1830        }1831      }1832    }18331834    main();18351836### REST18371838    curl -s -X POST \1839      "https://generativelanguage.googleapis.com/v1beta/interactions" \1840        -H "x-goog-api-key: $GEMINI_API_KEY" \1841        -H 'Content-Type: application/json' \1842        -d "{1843          \"model\": \"gemini-3.1-flash-image\",1844          \"input\": [1845            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},1846            {\"type\": \"text\", \"text\": \"Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged.\"}1847          ]1848        }"18491850|---|---|1851| Input | Output |1852| ![A wide shot of a modern, well-lit living room...](https://ai.google.dev/static/gemini-api/docs/images/living_room.png) A wide shot of a modern, well-lit living room... | ![Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa...](https://ai.google.dev/static/gemini-api/docs/images/living_room_edited.png) Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa... |18531854#### 3. Style transfer18551856Provide an image and ask the model to recreate its content in a different1857artistic style.18581859### Template18601861    Transform the provided photograph of [subject] into the artistic style of [artist/art style]. Preserve the original composition but render it with [description of stylistic elements].18621863### Prompt18641865    "Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."18661867### Python18681869    from google import genai1870    from PIL import Image1871    import base6418721873    client = genai.Client()18741875    with open('/path/to/your/city.png', 'rb') as f:1876        image_bytes = f.read()1877    text_input = """Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."""18781879    interaction = client.interactions.create(1880        model="gemini-3.1-flash-image",1881        input=[1882            {1883                "type": "image",1884                "data": base64.b64encode(image_bytes).decode('utf-8'),1885                "mime_type": "image/png"1886            },1887            {"type": "text", "text": text_input}1888        ],1889    )18901891    for step in interaction.steps:1892        if step.type == "model_output":1893            for content_block in step.content:1894                if content_block.type == "text":1895                    print(content_block.text)1896                elif content_block.type == "image":1897                    with open("city_style_transfer.png", "wb") as f:1898                        f.write(base64.b64decode(content_block.data))18991900### JavaScript19011902    import { GoogleGenAI } from "@google/genai";1903    import * as fs from "node:fs";19041905    async function main() {1906      const ai = new GoogleGenAI({});1907      const imageData = fs.readFileSync("/path/to/your/city.png");1908      const base64Image = imageData.toString("base64");19091910      const interaction = await ai.interactions.create({1911        model: "gemini-3.1-flash-image",1912        input: [1913          {1914            type: "image",1915            mime_type: "image/png",1916            data: base64Image1917          },1918          { type: "text", text: "Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows." },1919        ],1920      });1921      for (const step of interaction.steps) {1922        if (step.type === "model_output") {1923          for (const contentBlock of step.content) {1924            if (contentBlock.type === "text") {1925              console.log(contentBlock.text);1926            } else if (contentBlock.type === "image") {1927              const buffer = Buffer.from(contentBlock.data, "base64");1928              fs.writeFileSync("city_style_transfer.png", buffer);1929            }1930          }1931        }1932      }1933    }19341935    main();19361937### REST19381939    curl -s -X POST \1940      "https://generativelanguage.googleapis.com/v1beta/interactions" \1941        -H "x-goog-api-key: $GEMINI_API_KEY" \1942        -H 'Content-Type: application/json' \1943        -d "{1944          \"model\": \"gemini-3.1-flash-image\",1945          \"input\": [1946            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},1947            {\"type\": \"text\", \"text\": \"Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows.\"}1948          ]1949        }"19501951|---|---|1952| Input | Output |1953| ![A photorealistic, high-resolution photograph of a busy city street...](https://ai.google.dev/static/gemini-api/docs/images/city.png) A photorealistic, high-resolution photograph of a busy city street... | ![Transform the provided photograph of a modern city street at night...](https://ai.google.dev/static/gemini-api/docs/images/city_style_transfer.png) Transform the provided photograph of a modern city street at night... |19541955#### 4. Advanced composition: Combining multiple images19561957Provide multiple images as context to create a new, composite scene. This is1958perfect for product mockups or creative collages.19591960### Template19611962    Create a new image by combining the elements from the provided images. Take1963    the [element from image 1] and place it with/on the [element from image 2].1964    The final image should be a [description of the final scene].19651966### Prompt19671968    "Create a professional e-commerce fashion photo. Take the blue floral dress1969    from the first image and let the woman from the second image wear it.1970    Generate a realistic, full-body shot of the woman wearing the dress, with1971    the lighting and shadows adjusted to match the outdoor environment."19721973### Python19741975    from google import genai1976    from PIL import Image1977    import base6419781979    client = genai.Client()19801981    with open('/path/to/your/dress.png', 'rb') as f:1982        dress_bytes = f.read()1983    with open('/path/to/your/model.png', 'rb') as f:1984        model_bytes = f.read()1985    text_input = """Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment."""19861987    interaction = client.interactions.create(1988        model="gemini-3.1-flash-image",1989        input=[1990            {1991                "type": "image",1992                "data": base64.b64encode(dress_bytes).decode('utf-8'),1993                "mime_type": "image/png"1994            },1995            {1996                "type": "image",1997                "data": base64.b64encode(model_bytes).decode('utf-8'),1998                "mime_type": "image/png"1999            },2000            {"type": "text", "text": text_input}2001        ],2002    )20032004    for step in interaction.steps:2005        if step.type == "model_output":2006            for content_block in step.content:2007                if content_block.type == "text":2008                    print(content_block.text)2009                elif content_block.type == "image":2010                    with open("fashion_ecommerce_shot.png", "wb") as f:2011                        f.write(base64.b64decode(content_block.data))20122013### JavaScript20142015    import { GoogleGenAI } from "@google/genai";2016    import * as fs from "node:fs";20172018    async function main() {2019      const ai = new GoogleGenAI({});20202021      const imagePath1 = "/path/to/your/dress.png";2022      const imageData1 = fs.readFileSync(imagePath1);2023      const base64Image1 = imageData1.toString("base64");2024      const imagePath2 = "/path/to/your/model.png";2025      const imageData2 = fs.readFileSync(imagePath2);2026      const base64Image2 = imageData2.toString("base64");20272028      const input = [2029        {2030          type: "image",2031          mime_type: "image/png",2032          data: base64Image12033        },2034        {2035          type: "image",2036          mime_type: "image/png",2037          data: base64Image22038        },2039        { type: "text", text: "Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment." },2040      ];20412042      const interaction = await ai.interactions.create({2043        model: "gemini-3.1-flash-image",2044        input: input,2045      });2046      for (const step of interaction.steps) {2047        if (step.type === "model_output") {2048          for (const contentBlock of step.content) {2049            if (contentBlock.type === "text") {2050              console.log(contentBlock.text);2051            } else if (contentBlock.type === "image") {2052              const buffer = Buffer.from(contentBlock.data, "base64");2053              fs.writeFileSync("fashion_ecommerce_shot.png", buffer);2054            }2055          }2056        }2057      }2058    }20592060    main();20612062### REST20632064    curl -s -X POST \2065      "https://generativelanguage.googleapis.com/v1beta/interactions" \2066        -H "x-goog-api-key: $GEMINI_API_KEY" \2067        -H 'Content-Type: application/json' \2068        -d "{2069          \"model\": \"gemini-3.1-flash-image\",2070          \"input\": [2071                {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_1>\"},2072                {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},2073                {\"type\": \"text\", \"text\": \"Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment.\"}2074          }]2075        }"20762077|---|---|---|2078| Input 1 | Input 2 | Output |2079| :dress: A blue floral summer dress on a neutral background | ![Full-body shot of a woman with her hair in a bun...](https://ai.google.dev/static/gemini-api/docs/images/model.png) Full-body shot of a woman with her hair in a bun... | ![A woman wearing a blue floral summer dress in an outdoor setting](https://ai.google.dev/static/gemini-api/docs/images/fashion_ecommerce_shot.png) A woman wearing a blue floral summer dress in an outdoor setting |20802081#### 5. High-fidelity detail preservation20822083To ensure critical details (like a face or logo) are preserved during an edit,2084describe them in great detail along with your edit request.20852086### Template20872088    Using the provided images, place [element from image 2] onto [element from2089    image 1]. Ensure that the features of [element from image 1] remain2090    completely unchanged. The added element should [description of how the2091    element should integrate].20922093### Prompt20942095    "Take the first image of the woman with brown hair, blue eyes, and a neutral2096    expression. Add the logo from the second image onto her black t-shirt.2097    Ensure the woman's face and features remain completely unchanged. The logo2098    should look like it's naturally printed on the fabric, following the folds2099    of the shirt."21002101### Python21022103    from google import genai2104    from PIL import Image2105    import base6421062107    client = genai.Client()21082109    with open('/path/to/your/woman.png', 'rb') as f:2110        woman_bytes = f.read()2111    with open('/path/to/your/logo.png', 'rb') as f:2112        logo_bytes = f.read()2113    text_input = """Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."""21142115    interaction = client.interactions.create(2116        model="gemini-3.1-flash-image",2117        input=[2118          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(woman_bytes).decode('utf-8')},2119          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(logo_bytes).decode('utf-8')},2120          {"type": "text", "text": text_input}2121        ],2122    )21232124    for step in interaction.steps:2125        if step.type == "model_output":2126            for content_block in step.content:2127                if content_block.type == "text":2128                    print(content_block.text)2129                elif content_block.type == "image":2130                    with open("woman_with_logo.png", "wb") as f:2131                        f.write(base64.b64decode(content_block.data))21322133### JavaScript21342135    import { GoogleGenAI } from "@google/genai";2136    import * as fs from "node:fs";21372138    async function main() {2139      const ai = new GoogleGenAI({});21402141      const imagePath1 = "/path/to/your/woman.png";2142      const imageData1 = fs.readFileSync(imagePath1);2143      const base64Image1 = imageData1.toString("base64");2144      const imagePath2 = "/path/to/your/logo.png";2145      const imageData2 = fs.readFileSync(imagePath2);2146      const base64Image2 = imageData2.toString("base64");21472148      const input = [2149        {"type": "image", "mime_type":"image/png", "data": base64Image1},2150        {"type": "image", "mime_type":"image/png", "data": base64Image2},2151        {"type": "text", "text": "Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."},2152      ];21532154      const interaction = await ai.interactions.create({2155        model: "gemini-3.1-flash-image",2156        input: input,2157      });2158      for (const step of interaction.steps) {2159        if (step.type === "model_output") {2160          for (const contentBlock of step.content) {2161            if (contentBlock.type === "text") {2162              console.log(contentBlock.text);2163            } else if (contentBlock.type === "image") {2164              const buffer = Buffer.from(contentBlock.data, "base64");2165              fs.writeFileSync("woman_with_logo.png", buffer);2166            }2167          }2168        }2169      }2170    }21712172    main();21732174### REST21752176    curl -s -X POST \2177      "https://generativelanguage.googleapis.com/v1beta/interactions" \2178        -H "x-goog-api-key: $GEMINI_API_KEY" \2179        -H 'Content-Type: application/json' \2180        -d "{2181          \"model\": \"gemini-3.1-flash-image\",2182          \"input\": [2183            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_1>\"},2184            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},2185            {\"type\": \"text\", \"text\": \"Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt.\"}2186          ]2187        }"21882189|---|---|---|2190| Input 1 | Input 2 | Output |2191| :woman: A professional headshot of a woman with brown hair and blue eyes... | ![Modern brand identifier with letters G and A](https://ai.google.dev/static/gemini-api/docs/images/logo.png) Modern brand identifier with letters G and A | ![Take the first image of the woman with brown hair, blue eyes, and a neutral expression...](https://ai.google.dev/static/gemini-api/docs/images/woman_with_logo.png) Take the first image of the woman with brown hair, blue eyes, and a neutral expression... |21922193#### 6. Bring something to life21942195Upload a rough sketch or drawing and ask the model to refine it into a2196finished image.21972198### Template21992200    Turn this rough [medium] sketch of a [subject] into a [style description]2201    photo. Keep the [specific features] from the sketch but add [new details/materials].22022203### Prompt22042205    "Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."22062207### Python22082209    from google import genai2210    from PIL import Image2211    import base6422122213    client = genai.Client()22142215    with open('/path/to/your/car_sketch.png', 'rb') as f:2216        sketch_bytes = f.read()2217    text_input = """Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."""22182219    interaction = client.interactions.create(2220        model="gemini-3.1-flash-image",2221        input=[2222          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(sketch_bytes).decode('utf-8')},2223          {"type": "text", "text": text_input}2224        ],2225    )22262227    for step in interaction.steps:2228        if step.type == "model_output":2229            for content_block in step.content:2230                if content_block.type == "text":2231                    print(content_block.text)2232                elif content_block.type == "image":2233                    with open("car_photo.png", "wb") as f:2234                        f.write(base64.b64decode(content_block.data))22352236### JavaScript22372238    import { GoogleGenAI } from "@google/genai";2239    import * as fs from "node:fs";22402241    async function main() {2242      const ai = new GoogleGenAI({});22432244      const imagePath = "/path/to/your/car_sketch.png";2245      const imageData = fs.readFileSync(imagePath);2246      const base64Image = imageData.toString("base64");22472248      const input = [2249        {"type": "image", "mime_type":"image/png", "data": base64Image},2250        {"type": "text", "text": "Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."},2251      ];22522253      const interaction = await ai.interactions.create({2254        model: "gemini-3.1-flash-image",2255        input: input,2256      });2257      for (const step of interaction.steps) {2258        if (step.type === "model_output") {2259          for (const contentBlock of step.content) {2260            if (contentBlock.type === "text") {2261              console.log(contentBlock.text);2262            } else if (contentBlock.type === "image") {2263              const buffer = Buffer.from(contentBlock.data, "base64");2264              fs.writeFileSync("car_photo.png", buffer);2265            }2266          }2267        }2268      }2269    }22702271    main();22722273### REST22742275    curl -s -X POST \2276      "https://generativelanguage.googleapis.com/v1beta/interactions" \2277        -H "x-goog-api-key: $GEMINI_API_KEY" \2278        -H 'Content-Type: application/json' \2279        -d "{2280          \"model\": \"gemini-3.1-flash-image\",2281          \"input\": [2282            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},2283            {\"type\": \"text\", \"text\": \"Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting.\"}2284          ]2285        }"22862287|---|---|2288| Input | Output |2289| ![Sketch of a car](https://ai.google.dev/static/gemini-api/docs/images/car-sketch.jpg) Rough sketch of a car | ![Output showing the final concept car](https://ai.google.dev/static/gemini-api/docs/images/car-photo.jpg) Polished photo of a car |22902291#### 7. Character consistency: 360 view22922293You can generate 360-degree views of a character by iteratively prompting for2294different angles. For best results, include previously generated images in2295subsequent prompts to maintain consistency. For complex poses, include a2296reference image of the selected pose.22972298### Template22992300    A studio portrait of [person] against [background], [looking forward/in profile looking right/etc.]23012302### Prompt23032304    A studio portrait of this man against white, in profile looking right23052306### Python23072308    from google import genai2309    from PIL import Image2310    import base6423112312    client = genai.Client()23132314    with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:2315        image_bytes = f.read()2316    text_input = """A studio portrait of this man against white, in profile looking right"""23172318    interaction = client.interactions.create(2319        model="gemini-3.1-flash-image",2320        input={2321          {"type": "text", "text": text_input},2322          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(image_bytes).decode('utf-8')}2323        },2324    )23252326    for step in interaction.steps:2327        if step.type == "model_output":2328            for content_block in step.content:2329                if content_block.type == "text":2330                    print(content_block.text)2331                elif content_block.type == "image":2332                    with open("man_right_profile.png", "wb") as f:2333                        f.write(base64.b64decode(content_block.data))23342335|---|---|---|2336| Input | Output 1 | Output 2 |2337| ![Original input of a man in white glasses](https://ai.google.dev/static/gemini-api/docs/images/man_in_white_glasses.jpg) Original image | ![Output of a man in white glasses looking right](https://ai.google.dev/static/gemini-api/docs/images/man_in_white_glasses_looking_right.jpg) Man in white glasses looking right | ![Output of a man in white glasses looking forward](https://ai.google.dev/static/gemini-api/docs/images/man_in_white_glasses_looking_forward.jpg) Man in white glasses looking forward |23382339### Best Practices23402341To elevate your results from good to great, incorporate these professional2342strategies into your workflow.23432344- **Be Hyper-Specific:** The more detail you provide, the more control you have. Instead of "fantasy armor," describe it: "ornate elven plate armor, etched with silver leaf patterns, with a high collar and pauldrons shaped like falcon wings."2345- **Provide Context and Intent:** Explain the *purpose* of the image. The model's understanding of context will influence the final output. For example, "Create a logo for a high-end, minimalist skincare brand" will yield better results than just "Create a logo."2346- **Iterate and Refine:** Don't expect a perfect image on the first try. Use the conversational nature of the model to make small changes. Follow up with prompts like, "That's great, but can you make the lighting a bit warmer?" or "Keep everything the same, but change the character's expression to be more serious."2347- **Use Step-by-Step Instructions:** For complex scenes with many elements, break your prompt into steps. "First, create a background of a serene, misty forest at dawn. Then, in the foreground, add a moss-covered ancient stone altar. Finally, place a single, glowing sword on top of the altar."2348- **Use "Semantic Negative Prompts":** Instead of saying "no cars," describe the intended scene positively: "an empty, deserted street with no signs of traffic."2349- **Control the Camera:** Use photographic and cinematic language to control the composition. Terms like `wide-angle shot`, `macro shot`, `low-angle2350  perspective`.23512352## Limitations23532354- For best performance, use the following languages: EN, ar-EG, de-DE, es-MX, fr-FR, hi-IN, id-ID, it-IT, ja-JP, ko-KR, pt-BR, ru-RU, ua-UA, vi-VN, zh-CN.2355- Image generation does not support audio inputs. Video inputs are only supported for Gemini 3.1 Flash Image.2356- The model won't always follow the exact number of image outputs that the user explicitly asks for.2357- `gemini-2.5-flash-image` works best with up to 3 images as input, while `gemini-3-pro-image` supports 5 images with high fidelity, and up to 14 images in total. `gemini-3.1-flash-image` supports character resemblance of up to 4 characters and the fidelity of up to 10 objects in a single workflow.2358- When generating text for an image, Gemini works best if you first generate the text and then ask for an image with the text.2359- `gemini-3.1-flash-image` Grounding with Google Search does not support using real-world images of people from web search at this time.2360- All generated images include a [SynthID watermark](https://ai.google.dev/responsible/docs/safeguards/synthid).23612362## Optional configurations23632364You can optionally configure the output format, aspect ratio, and image size using the `response_format` parameter.23652366### Output format23672368The model defaults to returning both text and image responses. You can configure the response to return only the generated images (omitting the conversational text) by specifying an image format in the `response_format` parameter.23692370To request multiple modalities (for example, both text and the generated image), pass an array of format entries to `response_format` instead.23712372### Python23732374    interaction = client.interactions.create(2375        model="gemini-3.1-flash-image",2376        input="Write a short poem about a starry night and generate an image of it.",2377        response_format=[2378            {"type": "text"},2379            {"type": "image"},2380        ],2381    )23822383### JavaScript23842385    const interaction = await ai.interactions.create({2386      model: "gemini-3.1-flash-image",2387      input: "Write a short poem about a starry night and generate an image of it.",2388      response_format: [2389        { type: "text" },2390        { type: "image" },2391      ],2392    });23932394### REST23952396    curl -s -X POST \2397      "https://generativelanguage.googleapis.com/v1beta/interactions" \2398      -H "x-goog-api-key: $GEMINI_API_KEY" \2399      -H 'Content-Type: application/json' \2400      -H "Api-Revision: 2026-05-20" \2401      -d '{2402        "model": "gemini-3.1-flash-image",2403        "input": "Write a short poem about a starry night and generate an image of it.",2404        "response_format": [2405          { "type": "text" },2406          { "type": "image" }2407        ]2408      }'24092410### Aspect ratios and image size24112412By default, the model matches the output image size to that of your input image, or otherwise generates 1:1 squares. You can control the aspect ratio and the size of the output image using the `aspect_ratio` and `image_size` fields under `response_format` when `type` is set to `"image"`.24132414### Python24152416    interaction = client.interactions.create(2417        model="gemini-3.1-flash-image",2418        input=prompt,2419        response_format={2420            "type": "image",2421            "aspect_ratio": "16:9",2422            "image_size": "2K",2423        },2424    )24252426### JavaScript24272428    const interaction = await ai.interactions.create({2429        model: "gemini-3.1-flash-image",2430        input: prompt,2431        response_format: {2432          type: "image",2433          aspect_ratio: "16:9",2434          image_size: "2K",2435        },2436      });24372438### REST24392440    curl -s -X POST \2441      "https://generativelanguage.googleapis.com/v1beta/interactions" \2442      -H "x-goog-api-key: $GEMINI_API_KEY" \2443      -H 'Content-Type: application/json' \2444      -H "Api-Revision: 2026-05-20" \2445      -d '{2446        "model": "gemini-3.1-flash-image",2447        "input": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",2448        "response_format": {2449          "type": "image",2450          "aspect_ratio": "16:9",2451          "image_size": "2K"2452        }2453      }'24542455The different ratios available and the size of the image generated are listed in2456the following tables:24572458### 3.1 Flash Image24592460| Aspect ratio | 512px resolution | 0.5K tokens | 1K resolution | 1K tokens | 2K resolution | 2K tokens | 4K resolution | 4K tokens |2461|---|---|---|---|---|---|---|---|---|2462| **1:1** | 512x512 | 747 | 1024x1024 | 1120 | 2048x2048 | 1120 | 4096x4096 | 2000 |2463| **1:4** | 256x1024 | 747 | 512x2048 | 1120 | 1024x4096 | 1120 | 2048x8192 | 2000 |2464| **1:8** | 192x1536 | 747 | 384x3072 | 1120 | 768x6144 | 1120 | 1536x12288 | 2000 |2465| **2:3** | 424x632 | 747 | 848x1264 | 1120 | 1696x2528 | 1120 | 3392x5056 | 2000 |2466| **3:2** | 632x424 | 747 | 1264x848 | 1120 | 2528x1696 | 1120 | 5056x3392 | 2000 |2467| **3:4** | 448x600 | 747 | 896x1200 | 1120 | 1792x2400 | 1120 | 3584x4800 | 2000 |2468| **4:1** | 1024x256 | 747 | 2048x512 | 1120 | 4096x1024 | 1120 | 8192x2048 | 2000 |2469| **4:3** | 600x448 | 747 | 1200x896 | 1120 | 2400x1792 | 1120 | 4800x3584 | 2000 |2470| **4:5** | 464x576 | 747 | 928x1152 | 1120 | 1856x2304 | 1120 | 3712x4608 | 2000 |2471| **5:4** | 576x464 | 747 | 1152x928 | 1120 | 2304x1856 | 1120 | 4608x3712 | 2000 |2472| **8:1** | 1536x192 | 747 | 3072x384 | 1120 | 6144x768 | 1120 | 12288x1536 | 2000 |2473| **9:16** | 384x688 | 747 | 768x1376 | 1120 | 1536x2752 | 1120 | 3072x5504 | 2000 |2474| **16:9** | 688x384 | 747 | 1376x768 | 1120 | 2752x1536 | 1120 | 5504x3072 | 2000 |2475| **21:9** | 792x168 | 747 | 1584x672 | 1120 | 3168x1344 | 1120 | 6336x2688 | 2000 |24762477### 3 Pro Image24782479| Aspect ratio | 1K resolution | 1K tokens | 2K resolution | 2K tokens | 4K resolution | 4K tokens |2480|---|---|---|---|---|---|---|2481| **1:1** | 1024x1024 | 1120 | 2048x2048 | 1120 | 4096x4096 | 2000 |2482| **2:3** | 848x1264 | 1120 | 1696x2528 | 1120 | 3392x5056 | 2000 |2483| **3:2** | 1264x848 | 1120 | 2528x1696 | 1120 | 5056x3392 | 2000 |2484| **3:4** | 896x1200 | 1120 | 1792x2400 | 1120 | 3584x4800 | 2000 |2485| **4:3** | 1200x896 | 1120 | 2400x1792 | 1120 | 4800x3584 | 2000 |2486| **4:5** | 928x1152 | 1120 | 1856x2304 | 1120 | 3712x4608 | 2000 |2487| **5:4** | 1152x928 | 1120 | 2304x1856 | 1120 | 4608x3712 | 2000 |2488| **9:16** | 768x1376 | 1120 | 1536x2752 | 1120 | 3072x5504 | 2000 |2489| **16:9** | 1376x768 | 1120 | 2752x1536 | 1120 | 5504x3072 | 2000 |2490| **21:9** | 1584x672 | 1120 | 3168x1344 | 1120 | 6336x2688 | 2000 |24912492### Gemini 2.5 Flash Image24932494| Aspect ratio | Resolution | Tokens |2495|---|---|---|2496| 1:1 | 1024x1024 | 1290 |2497| 2:3 | 832x1248 | 1290 |2498| 3:2 | 1248x832 | 1290 |2499| 3:4 | 864x1184 | 1290 |2500| 4:3 | 1184x864 | 1290 |2501| 4:5 | 896x1152 | 1290 |2502| 5:4 | 1152x896 | 1290 |2503| 9:16 | 768x1344 | 1290 |2504| 16:9 | 1344x768 | 1290 |2505| 21:9 | 1536x672 | 1290 |25062507## Model selection25082509Choose the model best suited for your specific use case.25102511- **Gemini 3.1 Flash Image (Nano Banana 2)** should be your2512  go-to image generation model, as the best all around performance and2513  intelligence to cost and latency balance. Check the model [pricing](https://ai.google.dev/gemini-api/docs/pricing#gemini-3.1-flash-image) and [capabilities](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-image) page for more2514  details.25152516- **Gemini 3 Pro Image (Nano Banana Pro)** is designed for2517  professional asset production and complex instructions. This model features2518  real-world grounding using Google Search, a default "Thinking" process that2519  refines composition prior to generation, and can generate images of up to 4K2520  resolutions. Check the model [pricing](https://ai.google.dev/gemini-api/docs/pricing#gemini-3-pro-image) and [capabilities](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-image) page for more2521  details.25222523- **Gemini 2.5 Flash Image (Nano Banana)** is designed for speed and2524  efficiency. This model is optimized for high-volume, low-latency tasks and2525  generates images at 1024px resolution. Check the model [pricing](https://ai.google.dev/gemini-api/docs/pricing#gemini-2.5-flash-image) and2526  [capabilities](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image) page for more2527  details.25282529### When to use Imagen25302531> [!WARNING]2532> Imagen models are deprecated and will be shut down on August 17, 2026. We recommend using Nano Banana models for all image generation tasks.25332534In addition to using Gemini's built-in image generation capabilities, you can2535also access [Imagen](https://ai.google.dev/gemini-api/docs/imagen), our specialized image generation2536model, through the Gemini API. Plan to migrate before the shutdown date.25372538## What's next25392540- Check out the [Veo guide](https://ai.google.dev/gemini-api/docs/video) to learn how to generate videos with the Gemini API.2541- To learn more about Gemini models, see [Gemini models](https://ai.google.dev/gemini-api/docs/models/gemini).
Files main
Menu

Theme