SPB Git

Repository Public

image-generation.md 168.9 KB 4,013 lines markdown

1# Nano Banana image generation23Prompt 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.45- Or build your own from prompts:6- ![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)7- ![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.   8  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."9- ![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."10- ![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."11- ![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."12- ![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"13- ![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."14- ![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."15- ![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."1617**Nano Banana** is the name for Gemini's native image generation capabilities.18Gemini can generate and process images conversationally19with text, images, video, or a combination. This lets you create, edit, and20iterate on visuals with unprecedented control.2122Nano Banana refers to four distinct models available in the Gemini API:2324- **Nano Banana 2 Lite ([Gemini 3.1 Flash Lite Image](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-image))25  (`gemini-3.1-flash-lite-image`):** Our fastest and cheapest Gemini image model, engineered for velocity and scale where speed and cost are the primary operational constraints. Not optimized for multiple reference inputs or multi-turn sequential editing.26- **Nano Banana 2 ([Gemini 3.1 Flash Image](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-image))27  (`gemini-3.1-flash-image`):** Serves as the most versatile model, generalist workhorse model for all tasks. It balances speed with state-of-the-art 4K generation, world knowledge, and reliable text rendering. Excelling at multiple reference image processing and consistency.28- **Nano Banana Pro ([Gemini 3 Pro Image](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-image))29  (`gemini-3-pro-image`):** The premium choice for the most complex visual tasks, offering the highest level of world knowledge, advanced localization, accurate brand consistency, and precision creative control.30- **Nano Banana ([Gemini 2.5 Flash Image](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image))31  (`gemini-2.5-flash-image`):** The legacy pioneer of the Nano Banana series. While it has been a reliable workhorse, we strongly recommend that customers transition to Nano Banana 2 Lite to experience enhanced quality, faster generation speeds, and lower API pricing.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:51        f.write(base64.b64decode(interaction.output_image.data))5253### JavaScript5455    import { GoogleGenAI } from "@google/genai";56    import * as fs from "node:fs";5758    async function main() {5960      const ai = new GoogleGenAI({});6162      const prompt =63        "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";6465      const interaction = await ai.interactions.create({66        model: "gemini-3.1-flash-image",67        input: prompt,68      });69      const generatedImage = interaction.output_image;70      if (generatedImage) {71        const buffer = Buffer.from(generatedImage.data, "base64");72        fs.writeFileSync("gemini-native-image.png", buffer);73        console.log("Image saved as gemini-native-image.png");74      }75    }7677    main();7879### Java8081    import com.google.genai.Client;82    import com.google.genai.gaos.models.interactions.CreateModelInteraction;83    import com.google.genai.gaos.models.interactions.Interaction;84    import com.google.genai.gaos.models.interactions.InteractionsInput;85    import com.google.genai.gaos.models.interactions.Model;86    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;87    import java.nio.file.Files;88    import java.nio.file.Paths;89    import java.util.Base64;9091    Client client = new Client();9293    CreateModelInteraction params =94        CreateModelInteraction.builder()95            .model(Model.of("gemini-3.1-flash-image"))96            .input(97                InteractionsInput.of(98                    "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"))99            .build();100101    Interaction interaction =102        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();103104    if (interaction.outputImage().isPresent()105        && interaction.outputImage().get().data().isPresent()) {106      byte[] imageBytes =107          Base64.getDecoder().decode(interaction.outputImage().get().data().get());108      Files.write(Paths.get("generated_image.png"), imageBytes);109    }110111### REST112113    curl -s -X POST \114      "https://generativelanguage.googleapis.com/v1beta/interactions" \115      -H "x-goog-api-key: $GEMINI_API_KEY" \116      -H "Content-Type: application/json" \117      -d '{118        "model": "gemini-3.1-flash-image",119        "input": [120          {"type": "text", "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}121        ]122      }'123124You can retrieve generated image data by using the `interaction.output_image`125property, which returns the last generated image block. For details on126convenience properties, see the127[Interactions overview](https://ai.google.dev/gemini-api/docs/interactions-overview#convenience-properties).128129> [!NOTE]130> **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/image-generation#interleaved-output) for an example.131132## Image editing (text-and-image-to-image)133134**Reminder** : Make sure you have the necessary rights to any images you upload.135Don't generate content that infringe on others' rights, including videos or136images that deceive, harass, or harm. Your use of this generative AI service is137subject to our [Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy).138139Provide an image and use text prompts to add, remove, or modify elements,140change the style, or adjust the color grading.141142The following example demonstrates uploading `base64` encoded images.143For multiple images, larger payloads, and supported MIME types, check the [Image144understanding](https://ai.google.dev/gemini-api/docs/image-understanding) page.145146### Python147148    from google import genai149    from PIL import Image150    import base64151152    client = genai.Client()153154    with open("/path/to/cat_image.png", "rb") as f:155        image_bytes = f.read()156157    interaction = client.interactions.create(158        model="gemini-3.1-flash-image",159        input=[160            {161              "type": "text",162              "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"163            },164            {165                "type": "image",166                "data": base64.b64encode(image_bytes).decode('utf-8'),167                "mime_type": "image/png"168            }169        ],170    )171172    with open("generated_image.png", "wb") as f:173        f.write(base64.b64decode(interaction.output_image.data))174175### JavaScript176177    import { GoogleGenAI } from "@google/genai";178    import * as fs from "node:fs";179180    async function main() {181182      const ai = new GoogleGenAI({});183184      const imagePath = "path/to/cat_image.png";185      const imageData = fs.readFileSync(imagePath);186      const base64Image = imageData.toString("base64");187188      const prompt = [189        { type: "text", text: "Create a picture of my cat eating a nano-banana in a" +190                "fancy restaurant under the Gemini constellation" },191        {192          type: "image",193          mime_type: "image/png",194          data: base64Image195        },196      ];197198      const interaction = await ai.interactions.create({199        model: "gemini-3.1-flash-image",200        input: prompt,201      });202      const generatedImage = interaction.output_image;203      if (generatedImage) {204        const buffer = Buffer.from(generatedImage.data, "base64");205        fs.writeFileSync("gemini-native-image.png", buffer);206        console.log("Image saved as gemini-native-image.png");207      }208    }209210    main();211212### Java213214    import com.google.genai.Client;215    import com.google.genai.gaos.models.interactions.Content;216    import com.google.genai.gaos.models.interactions.CreateModelInteraction;217    import com.google.genai.gaos.models.interactions.ImageContent;218    import com.google.genai.gaos.models.interactions.ImageContentMimeType;219    import com.google.genai.gaos.models.interactions.Interaction;220    import com.google.genai.gaos.models.interactions.InteractionsInput;221    import com.google.genai.gaos.models.interactions.Model;222    import com.google.genai.gaos.models.interactions.TextContent;223    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;224    import java.nio.file.Files;225    import java.nio.file.Paths;226    import java.util.Arrays;227    import java.util.Base64;228    import java.util.List;229230    Client client = new Client();231232    byte[] inputBytes = Files.readAllBytes(Paths.get("/path/to/cat_image.png"));233    String base64Image = Base64.getEncoder().encodeToString(inputBytes);234235    Content textContent =236        TextContent.builder()237            .text("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme")238            .build();239    Content imageContent =240        ImageContent.builder()241            .data(base64Image)242            .mimeType(ImageContentMimeType.IMAGE_PNG)243            .build();244245    List<Content> contents = Arrays.asList(textContent, imageContent);246247    CreateModelInteraction params =248        CreateModelInteraction.builder()249            .model(Model.of("gemini-3.1-flash-image"))250            .input(InteractionsInput.ofContent(contents))251            .build();252253    Interaction interaction =254        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();255256    if (interaction.outputImage().isPresent()257        && interaction.outputImage().get().data().isPresent()) {258      byte[] outputBytes =259          Base64.getDecoder().decode(interaction.outputImage().get().data().get());260      Files.write(Paths.get("generated_image.png"), outputBytes);261    }262263### REST264265    curl -s -X POST \266      "https://generativelanguage.googleapis.com/v1beta/interactions" \267        -H "x-goog-api-key: $GEMINI_API_KEY" \268        -H 'Content-Type: application/json' \269        -d "{270          \"model\": \"gemini-3.1-flash-image\",271          \"input\": [272            {\"type\": \"text\", \"text\": \"Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"},273            {274              \"type\": \"image\",275              \"mime_type\": \"image/jpeg\",276              \"data\": \"<BASE64_IMAGE_DATA>\"277            }278          ]279        }"280281### Multi-turn image editing282283Keep generating and editing images conversationally. Multi-turn284conversation is the recommended way to iterate on images. The following285example shows a prompt to generate an infographic about photosynthesis.286287### Python288289    from google import genai290    import base64291292    client = genai.Client()293294    interaction = client.interactions.create(295        model="gemini-3.1-flash-image",296        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.",297        tools=[{"type": "google_search"}],298    )299300    with open("photosynthesis.png", "wb") as f:301        f.write(base64.b64decode(interaction.output_image.data))302303### JavaScript304305    import { GoogleGenAI } from "@google/genai";306    import * as fs from "node:fs";307308    const ai = new GoogleGenAI({});309310    async function main() {311      const interaction = await ai.interactions.create({312        model: "gemini-3.1-flash-image",313        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.",314        tools: [{"type": "google_search"}],315      });316317      const generatedImage = interaction.output_image;318      if (generatedImage) {319        const buffer = Buffer.from(generatedImage.data, "base64");320        fs.writeFileSync("photosynthesis.png", buffer);321        console.log("Image saved as photosynthesis.png");322      }323    }324325    await main();326327### Java328329    import com.google.genai.Client;330    import com.google.genai.gaos.models.interactions.CreateModelInteraction;331    import com.google.genai.gaos.models.interactions.GoogleSearch;332    import com.google.genai.gaos.models.interactions.Interaction;333    import com.google.genai.gaos.models.interactions.InteractionsInput;334    import com.google.genai.gaos.models.interactions.Model;335    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;336    import java.nio.file.Files;337    import java.nio.file.Paths;338    import java.util.Arrays;339    import java.util.Base64;340341    Client client = new Client();342343    CreateModelInteraction params =344        CreateModelInteraction.builder()345            .model(Model.of("gemini-3.1-flash-image"))346            .input(347                InteractionsInput.of(348                    "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."))349            .tools(Arrays.asList(new GoogleSearch()))350            .build();351352    Interaction interaction =353        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();354355    if (interaction.outputImage().isPresent()356        && interaction.outputImage().get().data().isPresent()) {357      byte[] imageBytes =358          Base64.getDecoder().decode(interaction.outputImage().get().data().get());359      Files.write(Paths.get("photosynthesis.png"), imageBytes);360    }361362### REST363364    curl -s -X POST \365      "https://generativelanguage.googleapis.com/v1beta/interactions" \366      -H "x-goog-api-key: $GEMINI_API_KEY" \367      -H "Content-Type: application/json" \368      -d '{369        "model": "gemini-3.1-flash-image",370        "input": [371          {"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."}372        ],373        "tools": [{"type": "google_search"}]374      }'375376![AI-generated infographic about photosynthesis](https://ai.google.dev/static/gemini-api/docs/images/infographic-eng.png) AI-generated infographic about photosynthesis377378You can then use the `previous_interaction_id` to change the language on the graphic to Spanish.379380### Python381382    interaction_2 = client.interactions.create(383        model="gemini-3.1-flash-image",384        input="Update this infographic to be in Spanish. Do not change any other elements of the image.",385        previous_interaction_id=interaction.id,386        response_format={387            "type": "image",388            "mime_type": "image/jpeg",389            "aspect_ratio": "16:9",390            "image_size": "2K"391        },392    )393394    generated_image = interaction_2.output_image395    if generated_image:396        with open("photosynthesis_spanish.png", "wb") as f:397            f.write(base64.b64decode(generated_image.data))398399### JavaScript400401    const interaction2 = await ai.interactions.create({402      model: "gemini-3.1-flash-image",403      input: "Update this infographic to be in Spanish. Do not change any other elements of the image.",404      previous_interaction_id: interaction.id,405      response_format: {406        type: "image",407        mime_type: "image/png",408        aspect_ratio: "16:9",409        image_size: "2K"410      },411    });412413    const generatedImage = interaction2.output_image;414    if (generatedImage) {415      const buffer = Buffer.from(generatedImage.data, "base64");416      fs.writeFileSync("photosynthesis_spanish.png", buffer);417    }418419### Java420421    import com.google.genai.Client;422    import com.google.genai.gaos.models.interactions.CreateModelInteraction;423    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;424    import com.google.genai.gaos.models.interactions.GoogleSearch;425    import com.google.genai.gaos.models.interactions.ImageResponseFormat;426    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;427    import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;428    import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;429    import com.google.genai.gaos.models.interactions.Interaction;430    import com.google.genai.gaos.models.interactions.InteractionsInput;431    import com.google.genai.gaos.models.interactions.Model;432    import com.google.genai.gaos.models.interactions.ResponseFormat;433    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;434    import java.nio.file.Files;435    import java.nio.file.Paths;436    import java.util.Arrays;437    import java.util.Base64;438439    Client client = new Client();440441    CreateModelInteraction turn1Params =442        CreateModelInteraction.builder()443            .model(Model.of("gemini-3.1-flash-image"))444            .input(445                InteractionsInput.of(446                    "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food."))447            .tools(Arrays.asList(new GoogleSearch()))448            .build();449450    Interaction interaction =451        client.interactions.create(CreateInteractionRequestBody.of(turn1Params)).interaction().get();452453    CreateModelInteractionResponseFormat format =454        CreateModelInteractionResponseFormat.of(455            ResponseFormat.of(456                ImageResponseFormat.builder()457                    .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)458                    .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))459                    .imageSize(ImageResponseFormatImageSize.TWO_K)460                    .build()));461462    CreateModelInteraction turn2Params =463        CreateModelInteraction.builder()464            .model(Model.of("gemini-3.1-flash-image"))465            .input(466                InteractionsInput.of(467                    "Update this infographic to be in Spanish. Do not change any other elements of the image."))468            .previousInteractionId(interaction.id().orElse(""))469            .responseFormat(format)470            .build();471472    Interaction interaction2 =473        client.interactions.create(CreateInteractionRequestBody.of(turn2Params)).interaction().get();474475    if (interaction2.outputImage().isPresent()476        && interaction2.outputImage().get().data().isPresent()) {477      byte[] imageBytes =478          Base64.getDecoder().decode(interaction2.outputImage().get().data().get());479      Files.write(Paths.get("photosynthesis_spanish.png"), imageBytes);480    }481482### REST483484    curl -s -X POST \485      "https://generativelanguage.googleapis.com/v1beta/interactions" \486      -H "x-goog-api-key: $GEMINI_API_KEY" \487      -H 'Content-Type: application/json' \488      -d '{489        "model": "gemini-3.1-flash-image",490        "input": "Update this infographic to be in Spanish. Do not change any other elements of the image.",491        "previous_interaction_id": "<PREVIOUS_INTERACTION_ID>",492        "response_format": {493          "type": "image",494          "mime_type": "image/jpeg",495          "aspect_ratio": "16:9",496          "image_size": "2K"497        }498      }'499500![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 Spanish501502## New with Gemini 3 image models503504Gemini 3 offers state-of-the-art image generation and editing models. Gemini 3.1505Flash Image is optimized for speed and high-volume use-cases, and Gemini 3506Pro Image is optimized for professional asset production.507Designed to tackle the most challenging workflows through advanced reasoning,508they excel at complex, multi-turn creation and modification tasks.509510- **High-resolution output** : Built-in generation capabilities for 1K, 2K, and 4K visuals.511  - **Gemini 3.1 Flash Image** adds the smaller 512px (0.5K) resolution.512  - **Gemini 3.1 Flash Lite Image** only supports 1K resolution.513- **Advanced text rendering**: Capable of generating legible, stylized text for infographics, menus, diagrams, and marketing assets.514- **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).515  - **Not supported by Gemini 3.1 Flash Lite Image model.**516  - **Gemini 3.1 Flash Image** adds the integration of Google Image Search Grounding alongside Web Search.517- **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.518- **Up to 14 reference images**: You can now mix up to 14 reference images to produce the final image.519- **New aspect ratios** : Gemini 3.1 Flash Lite Image adds `1:1`, `3:2`, `2:3`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` [aspect ratios](https://ai.google.dev/gemini-api/docs/image-generation#aspect_ratios_and_image_size).520521### Use up to 14 reference images522523Gemini 3 image models let you to mix up to 14 reference images. These 14 images524can include the following:525526| Gemini 3.1 Flash Lite Image | Gemini 3.1 Flash Image | Gemini 3 Pro Image |527|---|---|---|528| Up to 14 images of objects with high-fidelity to include in the final image | 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 |529| N/A | Up to 4 images of characters to maintain character consistency | Up to 5 images of characters to maintain character consistency |530| N/A | N/A | Up to 3 images to be used as style references |531532### Python533534    from google import genai535    from google.genai import types536    from PIL import Image537    import base64538539    prompt = "An office group photo of these people, they are making funny faces."540541    client = genai.Client()542543    interaction = client.interactions.create(544        model="gemini-3.1-flash-image",545        input=[546            {547                "type": "text",548                "text": prompt,549            },550            {551                "type": "image",552                "data": base64.b64encode(image_bytes).decode('utf-8'),553                "mime_type": "image/png"554            },555            {556                "type": "image",557                "data": base64.b64encode(image_bytes).decode('utf-8'),558                "mime_type": "image/png"559            },560            {561                "type": "image",562                "data": base64.b64encode(image_bytes).decode('utf-8'),563                "mime_type": "image/png"564            },565            {566                "type": "image",567                "data": base64.b64encode(image_bytes).decode('utf-8'),568                "mime_type": "image/png"569            },570            {571                "type": "image",572                "data": base64.b64encode(image_bytes).decode('utf-8'),573                "mime_type": "image/png"574            },575        ],576        response_format={577            "type": "image",578            "aspect_ratio": "5:4",579            "image_size": "2K"580        },581    )582583    with open("office.png", "wb") as f:584        f.write(base64.b64decode(interaction.output_image.data))585586### JavaScript587588    import { GoogleGenAI } from "@google/genai";589    import * as fs from "node:fs";590591    async function main() {592      const ai = new GoogleGenAI({});593594      const input = [595        {596          type: "text",597          text: "An office group photo of these people, they are making funny faces.",598        },599        { type: "image", mime_type: "image/jpeg", data: base64ImageFile1 },600        { type: "image", mime_type: "image/jpeg", data: base64ImageFile2 },601        { type: "image", mime_type: "image/jpeg", data: base64ImageFile3 },602        { type: "image", mime_type: "image/jpeg", data: base64ImageFile4 },603        { type: "image", mime_type: "image/jpeg", data: base64ImageFile5 },604      ];605606      const interaction = await ai.interactions.create({607        model: "gemini-3.1-flash-image",608        input: input,609        response_format: {610          type: "image",611          aspect_ratio: "5:4",612          image_size: "2K",613        },614      });615616      const buffer = Buffer.from(interaction.output_image.data, 'base64');617618      fs.writeFileSync('office.png', buffer);619    }620621    main();622623### Java624625    import com.google.genai.Client;626    import com.google.genai.gaos.models.interactions.Content;627    import com.google.genai.gaos.models.interactions.CreateModelInteraction;628    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;629    import com.google.genai.gaos.models.interactions.ImageContent;630    import com.google.genai.gaos.models.interactions.ImageContentMimeType;631    import com.google.genai.gaos.models.interactions.ImageResponseFormat;632    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;633    import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;634    import com.google.genai.gaos.models.interactions.Interaction;635    import com.google.genai.gaos.models.interactions.InteractionsInput;636    import com.google.genai.gaos.models.interactions.Model;637    import com.google.genai.gaos.models.interactions.ResponseFormat;638    import com.google.genai.gaos.models.interactions.TextContent;639    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;640    import java.nio.file.Files;641    import java.nio.file.Paths;642    import java.util.Arrays;643    import java.util.Base64;644    import java.util.List;645646    String prompt = "An office group photo of these people, they are making funny faces.";647648    byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/person.png"));649    String base64Image = Base64.getEncoder().encodeToString(imageBytes);650651    Content textContent = TextContent.builder().text(prompt).build();652    Content imageContent =653        ImageContent.builder()654            .data(base64Image)655            .mimeType(ImageContentMimeType.IMAGE_PNG)656            .build();657658    List<Content> contents =659        Arrays.asList(660            textContent,661            imageContent,662            imageContent,663            imageContent,664            imageContent,665            imageContent);666667    CreateModelInteractionResponseFormat format =668        CreateModelInteractionResponseFormat.of(669            ResponseFormat.of(670                ImageResponseFormat.builder()671                    .aspectRatio(ImageResponseFormatAspectRatio.of("5:4"))672                    .imageSize(ImageResponseFormatImageSize.TWO_K)673                    .build()));674675    Client client = new Client();676677    CreateModelInteraction params =678        CreateModelInteraction.builder()679            .model(Model.of("gemini-3.1-flash-image"))680            .input(InteractionsInput.ofContent(contents))681            .responseFormat(format)682            .build();683684    Interaction interaction =685        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();686687    if (interaction.outputImage().isPresent()688        && interaction.outputImage().get().data().isPresent()) {689      byte[] outBytes =690          Base64.getDecoder().decode(interaction.outputImage().get().data().get());691      Files.write(Paths.get("office.png"), outBytes);692    }693694### REST695696    curl -s -X POST \697      "https://generativelanguage.googleapis.com/v1beta/interactions" \698        -H "x-goog-api-key: $GEMINI_API_KEY" \699        -H 'Content-Type: application/json' \700        -d "{701          \"model\": \"gemini-3.1-flash-image\",702          \"input\": [703            {\"type\": \"text\", \"text\": \"An office group photo of these people, they are making funny faces.\"},704            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_1>\"},705            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_2>\"},706            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_3>\"},707            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_4>\"},708            {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_5>\"}709          ],710          \"response_format\": {711            \"type\": \"image\",712            \"aspect_ratio\": \"5:4\",713            \"image_size\": \"2K\"714          }715        }"716717![AI-generated office group photo](https://ai.google.dev/static/gemini-api/docs/images/office-group-photo.jpeg) AI-generated office group photo718719### Grounding with Google Search720721Use the [Google Search tool](https://ai.google.dev/gemini-api/docs/google-search) to generate images722based on real-time information, such as weather forecasts, stock charts, or723recent events.724725Note that when using Grounding with Google Search with image generation,726image-based search results are not passed to the generation model and are727excluded from the response (see [Grounding with Google Image Search](https://ai.google.dev/gemini-api/docs/image-generation#image-search))728729### Python730731    from google import genai732    from google.genai import types733    import base64734    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"735736    client = genai.Client()737738    interaction = client.interactions.create(739        model="gemini-3.1-flash-image",740        input=prompt,741        tools=[{"type": "google_search"}],742        response_format={743            "type": "image",744            "mime_type": "image/jpeg",745            "aspect_ratio": "16:9"746        },747    )748749    with open("weather.png", "wb") as f:750        f.write(base64.b64decode(interaction.output_image.data))751752### JavaScript753754    import { GoogleGenAI } from "@google/genai";755    import * as fs from "node:fs";756757    async function main() {758      const ai = new GoogleGenAI({});759760      const interaction = await ai.interactions.create({761        model: "gemini-3.1-flash-image",762        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",763        tools: [{"type": "google_search"}],764        response_format: {765          type: "image",766          mime_type: "image/png",767          aspect_ratio: "16:9",768          image_size: "2K"769        },770      });771772      const buffer = Buffer.from(interaction.output_image.data, 'base64');773774      fs.writeFileSync('weather.png', buffer);775    }776777    main();778779### Java780781    import com.google.genai.Client;782    import com.google.genai.gaos.models.interactions.CreateModelInteraction;783    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;784    import com.google.genai.gaos.models.interactions.GoogleSearch;785    import com.google.genai.gaos.models.interactions.ImageResponseFormat;786    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;787    import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;788    import com.google.genai.gaos.models.interactions.Interaction;789    import com.google.genai.gaos.models.interactions.InteractionsInput;790    import com.google.genai.gaos.models.interactions.Model;791    import com.google.genai.gaos.models.interactions.ResponseFormat;792    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;793    import java.nio.file.Files;794    import java.nio.file.Paths;795    import java.util.Arrays;796    import java.util.Base64;797798    String prompt =799        "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";800801    Client client = new Client();802803    CreateModelInteractionResponseFormat format =804        CreateModelInteractionResponseFormat.of(805            ResponseFormat.of(806                ImageResponseFormat.builder()807                    .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)808                    .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))809                    .build()));810811    CreateModelInteraction params =812        CreateModelInteraction.builder()813            .model(Model.of("gemini-3.1-flash-image"))814            .input(InteractionsInput.of(prompt))815            .tools(Arrays.asList(new GoogleSearch()))816            .responseFormat(format)817            .build();818819    Interaction interaction =820        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();821822    if (interaction.outputImage().isPresent()823        && interaction.outputImage().get().data().isPresent()) {824      byte[] imageBytes =825          Base64.getDecoder().decode(interaction.outputImage().get().data().get());826      Files.write(Paths.get("weather.png"), imageBytes);827    }828829### REST830831    curl -s -X POST \832      "https://generativelanguage.googleapis.com/v1beta/interactions" \833      -H "x-goog-api-key: $GEMINI_API_KEY" \834      -H "Content-Type: application/json" \835      -d '{836        "model": "gemini-3.1-flash-image",837        "input": [838          {"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"}839        ],840        "tools": [{"type": "google_search"}],841        "response_format": {842          "type": "image",843          "mime_type": "image/jpeg",844          "aspect_ratio": "16:9"845        }846      }'847848![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 Francisco849850The response includes `google_search_call` and `google_search_result` steps,851along with inline `url_citation` annotations on the text step:852853- **`google_search_result`** : Contains `search_suggestions`, an HTML snippet for rendering search suggestions in your UI.854- **`url_citation` annotations**: Inline citations on the text step linking parts of the response to their web sources.855856### Grounding with Google Search for images (3.1 Flash)857858> [!NOTE]859> **Note:** This feature is only available for the Gemini 3.1 Flash Image model.860861Grounding with Google Image Search allows models to use web images retrieved via862Google Image Search as visual context for image generation. Image Search is a863new search type within the existing Grounding with Google Search tool,864functioning alongside standard [Web Search](https://ai.google.dev/gemini-api/docs/image-generation#use-with-grounding).865866To enable Image Search, configure the `google_search` tool in your API request867and specify `image_search` within the `search_types` array. Image Search can be868used independently or together with Web Search.869870### Python871872    from google import genai873874    client = genai.Client()875876    interaction = client.interactions.create(877        model="gemini-3.1-flash-image",878        input="A detailed painting of a Timareta butterfly resting on a flower",879        tools=[{880          "type": "google_search",881          "search_types": ["web_search", "image_search"]882        }]883    )884885### JavaScript886887    import { GoogleGenAI } from "@google/genai";888889    async function main() {890      const ai = new GoogleGenAI({});891892      const interaction = await ai.interactions.create({893        model: "gemini-3.1-flash-image",894        input: "A detailed painting of a Timareta butterfly resting on a flower",895        tools: [{896          "type": "google_search",897          "search_types": ["web_search", "image_search"]898        }]899      });900    }901902    main();903904### Java905906    import com.google.genai.Client;907    import com.google.genai.gaos.models.interactions.CreateModelInteraction;908    import com.google.genai.gaos.models.interactions.GoogleSearch;909    import com.google.genai.gaos.models.interactions.GoogleSearchSearchType;910    import com.google.genai.gaos.models.interactions.Interaction;911    import com.google.genai.gaos.models.interactions.InteractionsInput;912    import com.google.genai.gaos.models.interactions.Model;913    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;914    import java.util.Arrays;915916    Client client = new Client();917918    GoogleSearch searchTool =919        GoogleSearch.builder()920            .searchTypes(921                Arrays.asList(922                    GoogleSearchSearchType.WEB_SEARCH, GoogleSearchSearchType.IMAGE_SEARCH))923            .build();924925    CreateModelInteraction params =926        CreateModelInteraction.builder()927            .model(Model.of("gemini-3.1-flash-image"))928            .input(929                InteractionsInput.of(930                    "A detailed painting of a Timareta butterfly resting on a flower"))931            .tools(Arrays.asList(searchTool))932            .build();933934    Interaction interaction =935        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();936937### REST938939    curl -s -X POST \940      "https://generativelanguage.googleapis.com/v1beta/interactions" \941      -H "x-goog-api-key: $GEMINI_API_KEY" \942      -H "Content-Type: application/json" \943      -d '{944        "model": "gemini-3.1-flash-image",945        "input": "A detailed painting of a Timareta butterfly resting on a flower",946        "tools": [{"type": "google_search", "search_types": ["web_search", "image_search"]}]947      }'948949**Display requirements**950951When you use Image Search within Grounding with Google Search, you must display952the `search_suggestions` from the `google_search_result` step. Full usage953requirements are detailed in the954[Terms of Service](https://ai.google.dev/gemini-api/terms#grounding-with-google-search).955956**Response**957958For grounded responses using image search, the API returns inline citations959and attribution metadata as part of the response steps:960961- **`url_citation` annotations** : Inline citations on the text content block962  within `model_output`, linking the generated content to its source.963964- **`google_search_result`** : Contains `search_suggestions`, an HTML965  snippet for rendering search suggestions in your UI.966967### Video-to-image generation (3.1 Flash and 3.1 Flash Lite)968969> [!NOTE]970> **Note:** This feature is only available for the Gemini 3.1 Flash Image and Gemini 3.1 Flash Lite Image models.971972Video-to-image generation allows you to generate new images using a video's context973as a multimodal reference. This is useful for creating high-quality video thumbnails, cinematic974posters, summary infographics, or new artwork inspired by a video scene.975976During generation, the model analyzes the video frames in context to extract visual themes977and key events, then uses them alongside your text prompt to synthesize the output image.978979You can pass public [YouTube URLs](https://ai.google.dev/gemini-api/docs/video-understanding#youtube)980directly in your API request or upload local video files using the981[Files API](https://ai.google.dev/gemini-api/docs/files).982983### Python984985    from google import genai986    from google.genai import types987    import base64988989    client = genai.Client()990991    interaction = client.interactions.create(992        model="gemini-3.1-flash-image",993        input=[994            {995                "type": "video",996                "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",997                "mime_type": "video/mp4"998            },999            {"type": "text", "text": "Generate a poster image that captures the key themes of this video."}1000        ],1001        response_format={"type": "image", "aspect_ratio": "16:9"}1002    )10031004    # Save the generated image part1005    for step in interaction.steps:1006        if step.type == "model_output":1007            for content_block in step.content:1008                if content_block.type == "text":1009                    print(content_block.text)1010                elif content_block.type == "image":1011                    with open("video_poster.png", "wb") as f:1012                        f.write(base64.b64decode(content_block.data))1013                    print("Image saved as video_poster.png")10141015### JavaScript10161017    import { GoogleGenAI } from "@google/genai";1018    import * as fs from "node:fs";10191020    async function main() {1021      const ai = new GoogleGenAI({});10221023      const interaction = await ai.interactions.create({1024        model: "gemini-3.1-flash-image",1025        input: [1026          {1027            type: "video",1028            uri: "https://www.youtube.com/watch?v=UTdfxFyOQTI",1029            mime_type: "video/mp4"1030          },1031          { type: "text", text: "Generate a poster image that captures the key themes of this video." }1032        ],1033        response_format: {1034          type: "image",1035          aspect_ratio: "16:9"1036        }1037      });10381039      for (const step of interaction.steps) {1040        if (step.type === "model_output") {1041          for (const contentBlock of step.content) {1042            if (contentBlock.type === "text") {1043              console.log(contentBlock.text);1044            } else if (contentBlock.type === "image") {1045              const buffer = Buffer.from(contentBlock.data, "base64");1046              fs.writeFileSync("video_poster.png", buffer);1047              console.log("Image saved as video_poster.png");1048            }1049          }1050        }1051      }1052    }10531054    main();10551056### Java10571058    import com.google.genai.Client;1059    import com.google.genai.gaos.models.interactions.Content;1060    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1061    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;1062    import com.google.genai.gaos.models.interactions.ImageContent;1063    import com.google.genai.gaos.models.interactions.ImageResponseFormat;1064    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;1065    import com.google.genai.gaos.models.interactions.Interaction;1066    import com.google.genai.gaos.models.interactions.InteractionsInput;1067    import com.google.genai.gaos.models.interactions.Model;1068    import com.google.genai.gaos.models.interactions.ModelOutputStep;1069    import com.google.genai.gaos.models.interactions.ResponseFormat;1070    import com.google.genai.gaos.models.interactions.Step;1071    import com.google.genai.gaos.models.interactions.TextContent;1072    import com.google.genai.gaos.models.interactions.VideoContent;1073    import com.google.genai.gaos.models.interactions.VideoContentMimeType;1074    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1075    import java.nio.file.Files;1076    import java.nio.file.Paths;1077    import java.util.Arrays;1078    import java.util.Base64;1079    import java.util.List;10801081    Client client = new Client();10821083    Content videoContent =1084        VideoContent.builder()1085            .uri("https://www.youtube.com/watch?v=UTdfxFyOQTI")1086            .mimeType(VideoContentMimeType.VIDEO_MP4)1087            .build();1088    Content textContent =1089        TextContent.builder()1090            .text("Generate a poster image that captures the key themes of this video.")1091            .build();10921093    List<Content> contents = Arrays.asList(videoContent, textContent);10941095    CreateModelInteractionResponseFormat format =1096        CreateModelInteractionResponseFormat.of(1097            ResponseFormat.of(1098                ImageResponseFormat.builder()1099                    .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))1100                    .build()));11011102    CreateModelInteraction params =1103        CreateModelInteraction.builder()1104            .model(Model.of("gemini-3.1-flash-image"))1105            .input(InteractionsInput.ofContent(contents))1106            .responseFormat(format)1107            .build();11081109    Interaction interaction =1110        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();11111112    if (interaction.steps().isPresent()) {1113      for (Step step : interaction.steps().get()) {1114        if (step instanceof ModelOutputStep) {1115          ModelOutputStep outputStep = (ModelOutputStep) step;1116          if (outputStep.content().isPresent()) {1117            for (Content block : outputStep.content().get()) {1118              if (block instanceof TextContent) {1119                System.out.println(((TextContent) block).text().orElse(""));1120              } else if (block instanceof ImageContent) {1121                ImageContent img = (ImageContent) block;1122                if (img.data().isPresent()) {1123                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());1124                  Files.write(Paths.get("video_poster.png"), imgBytes);1125                  System.out.println("Image saved as video_poster.png");1126                }1127              }1128            }1129          }1130        }1131      }1132    }11331134### REST11351136    curl -s -X POST \1137      "https://generativelanguage.googleapis.com/v1beta/interactions" \1138      -H "x-goog-api-key: $GEMINI_API_KEY" \1139      -H 'Content-Type: application/json' \1140      -d '{1141        "model": "gemini-3.1-flash-image",1142        "input": [1143          {1144            "type": "video",1145            "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",1146            "mime_type": "video/mp4"1147          },1148          {1149            "type": "text",1150            "text": "Generate a poster image that captures the key themes of this video."1151          }1152        ],1153        "response_format": {1154          "type": "image",1155          "aspect_ratio": "16:9"1156        }1157      }'11581159![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 video11601161### Generate images up to 4K resolution11621163Gemini 3 image models generate 1K images by default but can also output 2K,11644K, and 512px (05.K) (Gemini 3.1 Flash Image only) images. To generate higher1165resolution assets, specify the `image_size` in the `response_format`.11661167> [!NOTE]1168> **Note:** **Gemini 3.1 Flash Lite image model** only supports 1K images.11691170You must use an uppercase 'K' (e.g. 512px (05.K), 1K, 2K, 4K). Lowercase1171parameters (e.g., 1k) will be rejected.11721173### Python11741175    from google import genai1176    from google.genai import types1177    import base6411781179    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."11801181    client = genai.Client()11821183    interaction = client.interactions.create(1184        model="gemini-3.1-flash-image",1185        input=prompt,1186        response_format={1187            "type": "image",1188            "mime_type": "image/jpeg",1189            "aspect_ratio": "1:1",1190            "image_size": "1K"1191        },1192    )11931194    print(interaction.output_text)11951196    with open("butterfly.png", "wb") as f:1197        f.write(base64.b64decode(interaction.output_image.data))11981199### JavaScript12001201    import { GoogleGenAI } from "@google/genai";1202    import * as fs from "node:fs";12031204    async function main() {1205      const ai = new GoogleGenAI({});12061207      const interaction = await ai.interactions.create({1208        model: "gemini-3.1-flash-image",1209        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.",1210        response_format: {1211          type: "image",1212          mime_type: "image/png",1213          aspect_ratio: "1:1",1214          image_size: "1K",1215        },1216      });12171218      console.log(interaction.output_text);12191220      const buffer = Buffer.from(interaction.output_image.data, 'base64');12211222      fs.writeFileSync('butterfly.png', buffer);1223    }12241225    main();12261227### Java12281229    import com.google.genai.Client;1230    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1231    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;1232    import com.google.genai.gaos.models.interactions.ImageResponseFormat;1233    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;1234    import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;1235    import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;1236    import com.google.genai.gaos.models.interactions.Interaction;1237    import com.google.genai.gaos.models.interactions.InteractionsInput;1238    import com.google.genai.gaos.models.interactions.Model;1239    import com.google.genai.gaos.models.interactions.ResponseFormat;1240    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1241    import java.nio.file.Files;1242    import java.nio.file.Paths;1243    import java.util.Base64;12441245    String prompt =1246        "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.";12471248    Client client = new Client();12491250    CreateModelInteractionResponseFormat format =1251        CreateModelInteractionResponseFormat.of(1252            ResponseFormat.of(1253                ImageResponseFormat.builder()1254                    .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)1255                    .aspectRatio(ImageResponseFormatAspectRatio.of("1:1"))1256                    .imageSize(ImageResponseFormatImageSize.ONE_K)1257                    .build()));12581259    CreateModelInteraction params =1260        CreateModelInteraction.builder()1261            .model(Model.of("gemini-3.1-flash-image"))1262            .input(InteractionsInput.of(prompt))1263            .responseFormat(format)1264            .build();12651266    Interaction interaction =1267        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();12681269    System.out.println(interaction.outputText().orElse(""));12701271    if (interaction.outputImage().isPresent()1272        && interaction.outputImage().get().data().isPresent()) {1273      byte[] imageBytes =1274          Base64.getDecoder().decode(interaction.outputImage().get().data().get());1275      Files.write(Paths.get("butterfly.png"), imageBytes);1276    }12771278### REST12791280    curl -s -X POST \1281      "https://generativelanguage.googleapis.com/v1beta/interactions" \1282      -H "x-goog-api-key: $GEMINI_API_KEY" \1283      -H "Content-Type: application/json" \1284      -d '{1285        "model": "gemini-3.1-flash-image",1286        "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.",1287        "response_format": {1288          "type": "image",1289          "mime_type": "image/jpeg",1290          "aspect_ratio": "1:1",1291          "image_size": "1K"1292        }1293      }'12941295The following is an example image generated from this prompt:1296![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.12971298### Thinking process12991300Gemini 3 image models are thinking models that use a reasoning1301process ("Thinking") for complex prompts. This feature is enabled by default and1302cannot be disabled in the API. To learn more about the thinking process, see1303the [Gemini Thinking](https://ai.google.dev/gemini-api/docs/thinking) guide.13041305The model generates up to two interim images to test composition and logic. The1306last image within Thinking is also the final rendered image.13071308You can check the thoughts that lead to the final image being produced.13091310### Python13111312    for step in interaction.steps:1313        if step.type == "thought":1314            for content_block in step.summary:1315                if content_block.type == "text":1316                    print(content_block.text)1317                elif content_block.type == "image":1318                    image = Image.open(io.BytesIO(base64.b64decode(content_block.data)))1319                    image.show()13201321### JavaScript13221323    for (const step of interaction.steps) {1324      if (step.type === "thought") {1325        for (const contentBlock of step.summary) {1326          if (contentBlock.type === "text") {1327            console.log(contentBlock.text);1328          } else if (contentBlock.type === "image") {1329            const buffer = Buffer.from(contentBlock.data, 'base64');1330            fs.writeFileSync('thought_image.png', buffer);1331          }1332        }1333      }1334    }13351336### Java13371338    import com.google.genai.Client;1339    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1340    import com.google.genai.gaos.models.interactions.ImageContent;1341    import com.google.genai.gaos.models.interactions.Interaction;1342    import com.google.genai.gaos.models.interactions.InteractionsInput;1343    import com.google.genai.gaos.models.interactions.Model;1344    import com.google.genai.gaos.models.interactions.Step;1345    import com.google.genai.gaos.models.interactions.TextContent;1346    import com.google.genai.gaos.models.interactions.ThoughtStep;1347    import com.google.genai.gaos.models.interactions.ThoughtSummaryContent;1348    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1349    import java.nio.file.Files;1350    import java.nio.file.Paths;1351    import java.util.Base64;13521353    Client client = new Client();13541355    CreateModelInteraction params =1356        CreateModelInteraction.builder()1357            .model(Model.of("gemini-3.1-flash-image"))1358            .input(1359                InteractionsInput.of(1360                    "A futuristic city built inside a giant glass bottle floating in space"))1361            .build();13621363    Interaction interaction =1364        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();13651366    if (interaction.steps().isPresent()) {1367      for (Step step : interaction.steps().get()) {1368        if (step instanceof ThoughtStep) {1369          ThoughtStep thoughtStep = (ThoughtStep) step;1370          if (thoughtStep.summary().isPresent()) {1371            for (ThoughtSummaryContent contentBlock : thoughtStep.summary().get()) {1372              if (contentBlock instanceof TextContent) {1373                System.out.println(((TextContent) contentBlock).text().orElse(""));1374              } else if (contentBlock instanceof ImageContent) {1375                ImageContent img = (ImageContent) contentBlock;1376                if (img.data().isPresent()) {1377                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());1378                  Files.write(Paths.get("thought_image.png"), imgBytes);1379                }1380              }1381            }1382          }1383        }1384      }1385    }13861387#### Interleaved text and images13881389While standard image generation models only output images, some advanced Gemini13903 models (such as `gemini-3-pro-image`) can generate interleaved1391content---like stories or instructional guides containing both text blocks and1392illustrations inside the same response.13931394Because the output is complex and interleaved, convenience properties like1395`.output_image` or `.output_text` will not capture the full sequence. To access1396and save interleaved content, you must manually iterate over `steps`:13971398### Python13991400    interaction = client.interactions.create(1401        model="gemini-3-pro-image",1402        input="Write the story of the lifecycle of a monarch butterfly, interleave illustrations",1403    )14041405    image_counter = 11406    for step in interaction.steps:1407        if step.type == "model_output":1408            for content_block in step.content:1409                if content_block.type == "text":1410                    print(content_block.text)1411                elif content_block.type == "image":1412                    filename = f"butterfly_lifecycle_{image_counter}.png"1413                    with open(filename, "wb") as f:1414                        f.write(base64.b64decode(content_block.data))1415                    print(f"\n[Saved illustration: {filename}]\n")1416                    image_counter += 114171418### JavaScript14191420    const interaction = await ai.interactions.create({1421        model: "gemini-3-pro-image",1422        input: "Write the story of the lifecycle of a monarch butterfly, interleave illustrations",1423    });14241425    let imageCounter = 1;1426    for (const step of interaction.steps) {1427      if (step.type === "model_output") {1428        for (const contentBlock of step.content) {1429          if (contentBlock.type === "text") {1430            console.log(contentBlock.text);1431          } else if (contentBlock.type === "image") {1432            const buffer = Buffer.from(contentBlock.data, "base64");1433            const filename = `butterfly_lifecycle_${imageCounter}.png`;1434            fs.writeFileSync(filename, buffer);1435            console.log(`\n[Saved illustration: ${filename}]\n`);1436            imageCounter++;1437          }1438        }1439      }1440    }14411442### Java14431444    import com.google.genai.Client;1445    import com.google.genai.gaos.models.interactions.Content;1446    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1447    import com.google.genai.gaos.models.interactions.ImageContent;1448    import com.google.genai.gaos.models.interactions.Interaction;1449    import com.google.genai.gaos.models.interactions.InteractionsInput;1450    import com.google.genai.gaos.models.interactions.Model;1451    import com.google.genai.gaos.models.interactions.ModelOutputStep;1452    import com.google.genai.gaos.models.interactions.Step;1453    import com.google.genai.gaos.models.interactions.TextContent;1454    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1455    import java.nio.file.Files;1456    import java.nio.file.Paths;1457    import java.util.Base64;14581459    Client client = new Client();14601461    CreateModelInteraction params =1462        CreateModelInteraction.builder()1463            .model(Model.of("gemini-3-pro-image"))1464            .input(1465                InteractionsInput.of(1466                    "Write the story of the lifecycle of a monarch butterfly, interleave illustrations"))1467            .build();14681469    Interaction interaction =1470        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();14711472    int imageCounter = 1;1473    if (interaction.steps().isPresent()) {1474      for (Step step : interaction.steps().get()) {1475        if (step instanceof ModelOutputStep) {1476          ModelOutputStep outputStep = (ModelOutputStep) step;1477          if (outputStep.content().isPresent()) {1478            for (Content contentBlock : outputStep.content().get()) {1479              if (contentBlock instanceof TextContent) {1480                System.out.println(((TextContent) contentBlock).text().orElse(""));1481              } else if (contentBlock instanceof ImageContent) {1482                ImageContent img = (ImageContent) contentBlock;1483                if (img.data().isPresent()) {1484                  String filename = String.format("butterfly_lifecycle_%d.png", imageCounter);1485                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());1486                  Files.write(Paths.get(filename), imgBytes);1487                  System.out.printf("%n[Saved illustration: %s]%n", filename);1488                  imageCounter++;1489                }1490              }1491            }1492          }1493        }1494      }1495    }14961497#### Controlling thinking levels14981499With Gemini 3.1 Flash Image and Gemini 3.1 Flash Lite Image, you can control the1500amount of thinking the model uses to balance quality and latency. The default1501`thinking_level` is `minimal`, and the supported levels are `minimal` and `high`.15021503### Python15041505    from google import genai1506    from PIL import Image1507    import base641508    import io15091510    client = genai.Client()15111512    interaction = client.interactions.create(1513        model="gemini-3.1-flash-image",1514        input="A futuristic city built inside a giant glass bottle floating in space",1515        generation_config={"thinking_level": "high"},1516    )15171518    print(interaction.output_text)15191520    image = Image.open(io.BytesIO(base64.b64decode(interaction.output_image.data)))15211522    image.show()15231524### JavaScript15251526    import { GoogleGenAI } from "@google/genai";1527    import * as fs from "node:fs";15281529    async function main() {1530      const ai = new GoogleGenAI({});15311532      const interaction = await ai.interactions.create({1533        model: "gemini-3.1-flash-image",1534        input: "A futuristic city built inside a giant glass bottle floating in space",1535        generation_config: { thinking_level: "high" },1536      });15371538      console.log(interaction.output_text);15391540      const buffer = Buffer.from(interaction.output_image.data, 'base64');15411542      fs.writeFileSync('image.png', buffer);1543    }1544    main();15451546### Java15471548    import com.google.genai.Client;1549    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1550    import com.google.genai.gaos.models.interactions.GenerationConfig;1551    import com.google.genai.gaos.models.interactions.Interaction;1552    import com.google.genai.gaos.models.interactions.InteractionsInput;1553    import com.google.genai.gaos.models.interactions.Model;1554    import com.google.genai.gaos.models.interactions.ThinkingLevel;1555    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1556    import java.nio.file.Files;1557    import java.nio.file.Paths;1558    import java.util.Base64;15591560    Client client = new Client();15611562    CreateModelInteraction params =1563        CreateModelInteraction.builder()1564            .model(Model.of("gemini-3.1-flash-image"))1565            .input(1566                InteractionsInput.of(1567                    "A futuristic city built inside a giant glass bottle floating in space"))1568            .generationConfig(GenerationConfig.builder().thinkingLevel(ThinkingLevel.HIGH).build())1569            .build();15701571    Interaction interaction =1572        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();15731574    System.out.println(interaction.outputText().orElse(""));15751576    if (interaction.outputImage().isPresent()1577        && interaction.outputImage().get().data().isPresent()) {1578      byte[] imageBytes =1579          Base64.getDecoder().decode(interaction.outputImage().get().data().get());1580      Files.write(Paths.get("futuristic_city.png"), imageBytes);1581    }15821583### REST15841585    curl -s -X POST \1586      "https://generativelanguage.googleapis.com/v1beta/interactions" \1587      -H "x-goog-api-key: $GEMINI_API_KEY" \1588      -H "Content-Type: application/json" \1589      -d '{1590        "model": "gemini-3.1-flash-image",1591        "input": "A futuristic city built inside a giant glass bottle floating in space",1592        "generation_config": {1593          "thinking_level": "high"1594        }1595      }'15961597Note that thinking tokens are billed by default for thinking models, as the1598[thinking process](https://ai.google.dev/gemini-api/docs/image-generation#thinking-process) always happens by default whether you view1599the process or not.16001601## Other image generation modes16021603Although Nano Banana image generation models are recommended for most use cases,1604you can also explore dedicated image generation models:16051606- **Imagen**: Google's legacy text-to-image models (shut down).1607- **[Veo](https://ai.google.dev/gemini-api/docs/video)**: Google's video generation model.16081609## Generate images in batch16101611All of the image generation capabilities described on this page can also be1612run as batch jobs using the1613[Batch API](https://ai.google.dev/gemini-api/docs/batch-api#image-generation), which is ideal if you1614need to generate many images.You get higher rate limits in exchange for a1615turnaround of up to 24 hours.16161617## Prompting guide and strategies16181619This section provides prompt examples and templates for common image generation1620and editing workflows. Each example includes a re-usable template and a1621sample prompt for the Interactions API.16221623### Prompts for generating images16241625The following examples show how to use text prompts to generate various types of1626images.16271628#### 1. Photorealistic scenes16291630Describe a scene in rich detail. The more specific you are, the more control you1631have over the results.16321633### Template16341635    A photorealistic [type of shot] of a [subject description] in a [setting1636    description]. [Description of the light]. Shot from a [camera angle]1637    with a [lens type].16381639### Prompt16401641    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.16421643### Python16441645    from google import genai1646    from google.genai import types1647    import base6416481649    client = genai.Client()16501651    interaction = client.interactions.create(1652        model="gemini-3.1-flash-image",1653        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.",1654        response_format=[1655            {1656                "type": "image",1657                "mime_type": "image/jpeg",1658                "aspect_ratio": "16:9",1659            }1660        ],1661    )16621663    print(interaction.output_text)16641665    with open("coral_reef.png", "wb") as f:16661667        f.write(base64.b64decode(interaction.output_image.data))16681669### JavaScript16701671    import { GoogleGenAI } from "@google/genai";1672    import * as fs from "node:fs";16731674    async function main() {1675      const ai = new GoogleGenAI({});16761677      const interaction = await ai.interactions.create({1678        model: "gemini-3.1-flash-image",1679        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.",1680        response_format: [1681          {1682            type: "image",1683            mime_type: "image/jpeg",1684            aspect_ratio: "16:9",1685          }1686        ],1687      });1688      console.log(interaction.output_text);16891690      const buffer = Buffer.from(interaction.output_image.data, 'base64');16911692      fs.writeFileSync('coral_reef.png', buffer);1693    }16941695    main();16961697### Java16981699    import com.google.genai.Client;1700    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1701    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;1702    import com.google.genai.gaos.models.interactions.ImageResponseFormat;1703    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;1704    import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;1705    import com.google.genai.gaos.models.interactions.Interaction;1706    import com.google.genai.gaos.models.interactions.InteractionsInput;1707    import com.google.genai.gaos.models.interactions.Model;1708    import com.google.genai.gaos.models.interactions.ResponseFormat;1709    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1710    import java.nio.file.Files;1711    import java.nio.file.Paths;1712    import java.util.Arrays;1713    import java.util.Base64;17141715    Client client = new Client();17161717    CreateModelInteractionResponseFormat format =1718        CreateModelInteractionResponseFormat.of(1719            Arrays.asList(1720                ResponseFormat.of(1721                    ImageResponseFormat.builder()1722                        .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)1723                        .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))1724                        .build())));17251726    CreateModelInteraction params =1727        CreateModelInteraction.builder()1728            .model(Model.of("gemini-3.1-flash-image"))1729            .input(1730                InteractionsInput.of(1731                    "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."))1732            .responseFormat(format)1733            .build();17341735    Interaction interaction =1736        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();17371738    System.out.println(interaction.outputText().orElse(""));17391740    if (interaction.outputImage().isPresent()1741        && interaction.outputImage().get().data().isPresent()) {1742      byte[] imageBytes =1743          Base64.getDecoder().decode(interaction.outputImage().get().data().get());1744      Files.write(Paths.get("coral_reef.png"), imageBytes);1745    }17461747### REST17481749    curl -s -X POST \1750      "https://generativelanguage.googleapis.com/v1beta/interactions" \1751      -H "x-goog-api-key: $GEMINI_API_KEY" \1752      -H "Content-Type: application/json" \1753      -d '{1754        "model": "gemini-3.1-flash-image",1755        "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.",1756        "response_format": {1757          "type": "image",1758          "mime_type": "image/png",1759          "aspect_ratio": "16:9"1760        }1761      }'17621763#### 2. Stylized illustrations \& stickers17641765Describe the artistic style, subject, and medium. Be specific about the visual1766detail (bold lines, colors, etc.) for consistent results.17671768### Template17691770    A [style] of a [subject, with details about accessories or actions]1771    doing [activity]. The design features [visual qualities, e.g., bold outlines,1772    cel-shading, etc.] and [color/background preference].17731774### Prompt17751776    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.17771778### Python17791780    from google import genai1781    import base6417821783    client = genai.Client()17841785    interaction = client.interactions.create(1786        model="gemini-3.1-flash-image",1787        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.",1788    )17891790    for step in interaction.steps:1791        if step.type == "model_output":1792            for content_block in step.content:1793                if content_block.type == "text":1794                    print(content_block.text)1795                elif content_block.type == "image":1796                    with open("red_panda_sticker.png", "wb") as f:1797                        f.write(base64.b64decode(content_block.data))17981799### JavaScript18001801    import { GoogleGenAI } from "@google/genai";1802    import * as fs from "node:fs";18031804    async function main() {1805      const ai = new GoogleGenAI({});18061807      const interaction = await ai.interactions.create({1808        model: "gemini-3.1-flash-image",1809        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.",1810      });1811      for (const step of interaction.steps) {1812        if (step.type === "model_output") {1813          for (const contentBlock of step.content) {1814            if (contentBlock.type === "text") {1815              console.log(contentBlock.text);1816            } else if (contentBlock.type === "image") {1817              const buffer = Buffer.from(contentBlock.data, "base64");1818              fs.writeFileSync("red_panda_sticker.png", buffer);1819            }1820          }1821        }1822      }1823    }18241825    main();18261827### Java18281829    import com.google.genai.Client;1830    import com.google.genai.gaos.models.interactions.Content;1831    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1832    import com.google.genai.gaos.models.interactions.ImageContent;1833    import com.google.genai.gaos.models.interactions.Interaction;1834    import com.google.genai.gaos.models.interactions.InteractionsInput;1835    import com.google.genai.gaos.models.interactions.Model;1836    import com.google.genai.gaos.models.interactions.ModelOutputStep;1837    import com.google.genai.gaos.models.interactions.Step;1838    import com.google.genai.gaos.models.interactions.TextContent;1839    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1840    import java.nio.file.Files;1841    import java.nio.file.Paths;1842    import java.util.Base64;18431844    Client client = new Client();18451846    CreateModelInteraction params =1847        CreateModelInteraction.builder()1848            .model(Model.of("gemini-3.1-flash-image"))1849            .input(1850                InteractionsInput.of(1851                    "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."))1852            .build();18531854    Interaction interaction =1855        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();18561857    if (interaction.steps().isPresent()) {1858      for (Step step : interaction.steps().get()) {1859        if (step instanceof ModelOutputStep) {1860          ModelOutputStep outputStep = (ModelOutputStep) step;1861          if (outputStep.content().isPresent()) {1862            for (Content contentBlock : outputStep.content().get()) {1863              if (contentBlock instanceof TextContent) {1864                System.out.println(((TextContent) contentBlock).text().orElse(""));1865              } else if (contentBlock instanceof ImageContent) {1866                ImageContent img = (ImageContent) contentBlock;1867                if (img.data().isPresent()) {1868                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());1869                  Files.write(Paths.get("red_panda_sticker.png"), imgBytes);1870                }1871              }1872            }1873          }1874        }1875      }1876    }18771878### REST18791880    curl -s -X POST \1881      "https://generativelanguage.googleapis.com/v1beta/interactions" \1882      -H "x-goog-api-key: $GEMINI_API_KEY" \1883      -H "Content-Type: application/json" \1884      -d '{1885        "model": "gemini-3.1-flash-image",1886        "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."1887      }'18881889![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...18901891#### 3. Accurate text in images18921893Gemini excels at rendering text. Be clear about the text, the font style1894(descriptively), and the overall design. Use Gemini 3 Pro Image for1895professional asset production.18961897### Template18981899    Create a [image type] for [brand/concept] with the text "[text to render]"1900    in a [font style]. The design should be [style description], with a1901    [color scheme].19021903### Prompt19041905    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.19061907### Python19081909    from google import genai1910    import base6419111912    client = genai.Client()19131914    interaction = client.interactions.create(1915        model="gemini-3.1-flash-image",1916        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.",1917        response_format={"type": "image", "aspect_ratio": "1:1"},1918    )19191920    for step in interaction.steps:1921        if step.type == "model_output":1922            for content_block in step.content:1923                if content_block.type == "text":1924                    print(content_block.text)1925                elif content_block.type == "image":1926                    with open("logo_example.jpg", "wb") as f:1927                        f.write(base64.b64decode(content_block.data))19281929### JavaScript19301931    import { GoogleGenAI } from "@google/genai";1932    import * as fs from "node:fs";19331934    async function main() {1935      const ai = new GoogleGenAI({});19361937      const interaction = await ai.interactions.create({1938        model: "gemini-3.1-flash-image",1939        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.",1940        response_format: { type: "image", aspect_ratio: "1:1" },1941      });1942      for (const step of interaction.steps) {1943        if (step.type === "model_output") {1944          for (const contentBlock of step.content) {1945            if (contentBlock.type === "text") {1946              console.log(contentBlock.text);1947            } else if (contentBlock.type === "image") {1948              const buffer = Buffer.from(contentBlock.data, "base64");1949              fs.writeFileSync("logo_example.jpg", buffer);1950            }1951          }1952        }1953      }1954    }19551956    main();19571958### Java19591960    import com.google.genai.Client;1961    import com.google.genai.gaos.models.interactions.Content;1962    import com.google.genai.gaos.models.interactions.CreateModelInteraction;1963    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;1964    import com.google.genai.gaos.models.interactions.ImageContent;1965    import com.google.genai.gaos.models.interactions.ImageResponseFormat;1966    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;1967    import com.google.genai.gaos.models.interactions.Interaction;1968    import com.google.genai.gaos.models.interactions.InteractionsInput;1969    import com.google.genai.gaos.models.interactions.Model;1970    import com.google.genai.gaos.models.interactions.ModelOutputStep;1971    import com.google.genai.gaos.models.interactions.ResponseFormat;1972    import com.google.genai.gaos.models.interactions.Step;1973    import com.google.genai.gaos.models.interactions.TextContent;1974    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;1975    import java.nio.file.Files;1976    import java.nio.file.Paths;1977    import java.util.Base64;19781979    Client client = new Client();19801981    CreateModelInteractionResponseFormat format =1982        CreateModelInteractionResponseFormat.of(1983            ResponseFormat.of(1984                ImageResponseFormat.builder()1985                    .aspectRatio(ImageResponseFormatAspectRatio.of("1:1"))1986                    .build()));19871988    CreateModelInteraction params =1989        CreateModelInteraction.builder()1990            .model(Model.of("gemini-3.1-flash-image"))1991            .input(1992                InteractionsInput.of(1993                    "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."))1994            .responseFormat(format)1995            .build();19961997    Interaction interaction =1998        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();19992000    if (interaction.steps().isPresent()) {2001      for (Step step : interaction.steps().get()) {2002        if (step instanceof ModelOutputStep) {2003          ModelOutputStep outputStep = (ModelOutputStep) step;2004          if (outputStep.content().isPresent()) {2005            for (Content contentBlock : outputStep.content().get()) {2006              if (contentBlock instanceof TextContent) {2007                System.out.println(((TextContent) contentBlock).text().orElse(""));2008              } else if (contentBlock instanceof ImageContent) {2009                ImageContent img = (ImageContent) contentBlock;2010                if (img.data().isPresent()) {2011                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());2012                  Files.write(Paths.get("logo_example.jpg"), imgBytes);2013                }2014              }2015            }2016          }2017        }2018      }2019    }20202021### REST20222023    curl -s -X POST \2024      "https://generativelanguage.googleapis.com/v1beta/interactions" \2025      -H "x-goog-api-key: $GEMINI_API_KEY" \2026      -H "Content-Type: application/json" \2027      -d '{2028        "model": "gemini-3.1-flash-image",2029        "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.",2030        "response_format": {2031          "type": "image",2032          "aspect_ratio": "1:1"2033        }2034      }'20352036![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'...20372038#### 4. Product mockups \& commercial photography20392040Perfect for creating clean, professional product shots for ecommerce,2041advertising, or branding.20422043### Template20442045    A high-resolution, studio-lit product photograph of a [product description]2046    on a [background surface/description]. The lighting is a [lighting setup,2047    e.g., three-point softbox setup] to [lighting purpose]. The camera angle is2048    a [angle type] to showcase [specific feature]. Ultra-realistic, with sharp2049    focus on [key detail]. [Aspect ratio].20502051### Prompt20522053    A high-resolution, studio-lit product photograph of a minimalist ceramic2054    coffee mug in matte black, presented on a polished concrete surface. The2055    lighting is a three-point softbox setup designed to create soft, diffused2056    highlights and eliminate harsh shadows. The camera angle is a slightly2057    elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with2058    sharp focus on the steam rising from the coffee. Square image.20592060### Python20612062    from google import genai2063    import base6420642065    client = genai.Client()20662067    interaction = client.interactions.create(2068        model="gemini-3.1-flash-image",2069        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.",2070    )20712072    for step in interaction.steps:2073        if step.type == "model_output":2074            for content_block in step.content:2075                if content_block.type == "text":2076                    print(content_block.text)2077                elif content_block.type == "image":2078                    with open("product_mockup.png", "wb") as f:2079                        f.write(base64.b64decode(content_block.data))20802081### JavaScript20822083    import { GoogleGenAI } from "@google/genai";2084    import * as fs from "node:fs";20852086    async function main() {2087      const ai = new GoogleGenAI({});20882089      const interaction = await ai.interactions.create({2090        model: "gemini-3.1-flash-image",2091        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.",2092      });2093      for (const step of interaction.steps) {2094        if (step.type === "model_output") {2095          for (const contentBlock of step.content) {2096            if (contentBlock.type === "text") {2097              console.log(contentBlock.text);2098            } else if (contentBlock.type === "image") {2099              const buffer = Buffer.from(contentBlock.data, "base64");2100              fs.writeFileSync("product_mockup.png", buffer);2101            }2102          }2103        }2104      }2105    }21062107    main();21082109### Java21102111    import com.google.genai.Client;2112    import com.google.genai.gaos.models.interactions.Content;2113    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2114    import com.google.genai.gaos.models.interactions.ImageContent;2115    import com.google.genai.gaos.models.interactions.Interaction;2116    import com.google.genai.gaos.models.interactions.InteractionsInput;2117    import com.google.genai.gaos.models.interactions.Model;2118    import com.google.genai.gaos.models.interactions.ModelOutputStep;2119    import com.google.genai.gaos.models.interactions.Step;2120    import com.google.genai.gaos.models.interactions.TextContent;2121    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2122    import java.nio.file.Files;2123    import java.nio.file.Paths;2124    import java.util.Base64;21252126    Client client = new Client();21272128    CreateModelInteraction params =2129        CreateModelInteraction.builder()2130            .model(Model.of("gemini-3.1-flash-image"))2131            .input(2132                InteractionsInput.of(2133                    "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."))2134            .build();21352136    Interaction interaction =2137        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();21382139    if (interaction.steps().isPresent()) {2140      for (Step step : interaction.steps().get()) {2141        if (step instanceof ModelOutputStep) {2142          ModelOutputStep outputStep = (ModelOutputStep) step;2143          if (outputStep.content().isPresent()) {2144            for (Content contentBlock : outputStep.content().get()) {2145              if (contentBlock instanceof TextContent) {2146                System.out.println(((TextContent) contentBlock).text().orElse(""));2147              } else if (contentBlock instanceof ImageContent) {2148                ImageContent img = (ImageContent) contentBlock;2149                if (img.data().isPresent()) {2150                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());2151                  Files.write(Paths.get("product_mockup.png"), imgBytes);2152                }2153              }2154            }2155          }2156        }2157      }2158    }21592160### REST21612162    curl -s -X POST \2163      "https://generativelanguage.googleapis.com/v1beta/interactions" \2164      -H "x-goog-api-key: $GEMINI_API_KEY" \2165      -H "Content-Type: application/json" \2166      -d '{2167        "model": "gemini-3.1-flash-image",2168        "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."2169      }'21702171![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...21722173#### 5. Minimalist \& negative space design21742175Excellent for creating backgrounds for websites, presentations, or marketing2176materials where text will be overlaid.21772178### Template21792180    A minimalist composition featuring a single [subject] positioned in the2181    [bottom-right/top-left/etc.] of the frame. The background is a vast, empty2182    [color] canvas, creating significant negative space. Soft, subtle lighting.2183    [Aspect ratio].21842185### Prompt21862187    A minimalist composition featuring a single, delicate red maple leaf2188    positioned in the bottom-right of the frame. The background is a vast, empty2189    off-white canvas, creating significant negative space for text. Soft,2190    diffused lighting from the top left. Square image.21912192### Python21932194    from google import genai2195    import base6421962197    client = genai.Client()21982199    interaction = client.interactions.create(2200        model="gemini-3.1-flash-image",2201        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.",2202    )22032204    for step in interaction.steps:2205        if step.type == "model_output":2206            for content_block in step.content:2207                if content_block.type == "text":2208                    print(content_block.text)2209                elif content_block.type == "image":2210                    with open("minimalist_design.png", "wb") as f:2211                        f.write(base64.b64decode(content_block.data))22122213### JavaScript22142215    import { GoogleGenAI } from "@google/genai";2216    import * as fs from "node:fs";22172218    async function main() {2219      const ai = new GoogleGenAI({});22202221      const interaction = await ai.interactions.create({2222        model: "gemini-3.1-flash-image",2223        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.",2224      });2225      for (const step of interaction.steps) {2226        if (step.type === "model_output") {2227          for (const contentBlock of step.content) {2228            if (contentBlock.type === "text") {2229              console.log(contentBlock.text);2230            } else if (contentBlock.type === "image") {2231              const buffer = Buffer.from(contentBlock.data, "base64");2232              fs.writeFileSync("minimalist_design.png", buffer);2233            }2234          }2235        }2236      }2237    }22382239    main();22402241### Java22422243    import com.google.genai.Client;2244    import com.google.genai.gaos.models.interactions.Content;2245    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2246    import com.google.genai.gaos.models.interactions.ImageContent;2247    import com.google.genai.gaos.models.interactions.Interaction;2248    import com.google.genai.gaos.models.interactions.InteractionsInput;2249    import com.google.genai.gaos.models.interactions.Model;2250    import com.google.genai.gaos.models.interactions.ModelOutputStep;2251    import com.google.genai.gaos.models.interactions.Step;2252    import com.google.genai.gaos.models.interactions.TextContent;2253    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2254    import java.nio.file.Files;2255    import java.nio.file.Paths;2256    import java.util.Base64;22572258    Client client = new Client();22592260    CreateModelInteraction params =2261        CreateModelInteraction.builder()2262            .model(Model.of("gemini-3.1-flash-image"))2263            .input(2264                InteractionsInput.of(2265                    "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."))2266            .build();22672268    Interaction interaction =2269        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();22702271    if (interaction.steps().isPresent()) {2272      for (Step step : interaction.steps().get()) {2273        if (step instanceof ModelOutputStep) {2274          ModelOutputStep outputStep = (ModelOutputStep) step;2275          if (outputStep.content().isPresent()) {2276            for (Content contentBlock : outputStep.content().get()) {2277              if (contentBlock instanceof TextContent) {2278                System.out.println(((TextContent) contentBlock).text().orElse(""));2279              } else if (contentBlock instanceof ImageContent) {2280                ImageContent img = (ImageContent) contentBlock;2281                if (img.data().isPresent()) {2282                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());2283                  Files.write(Paths.get("minimalist_design.png"), imgBytes);2284                }2285              }2286            }2287          }2288        }2289      }2290    }22912292### REST22932294    curl -s -X POST \2295      "https://generativelanguage.googleapis.com/v1beta/interactions" \2296      -H "x-goog-api-key: $GEMINI_API_KEY" \2297      -H "Content-Type: application/json" \2298      -d '{2299        "model": "gemini-3.1-flash-image",2300        "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."2301      }'23022303![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...23042305#### 6. Sequential art (comic panel / storyboard)23062307Builds on character consistency and scene description to create panels for2308visual storytelling. For accuracy with text and storytelling ability, these2309prompts work best with Gemini 3 Pro and Gemini 3.1 Flash Image.23102311### Template23122313    Make a 3 panel comic in a [style]. Put the character in a [type of scene].23142315### Prompt23162317    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.23182319### Python23202321    from google import genai2322    from PIL import Image2323    import base6423242325    client = genai.Client()23262327    with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:2328        image_bytes = f.read()2329    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."23302331    interaction = client.interactions.create(2332        model="gemini-3.1-flash-image",2333        input=[2334            {"type": "text", "text": text_input},2335            {2336                "type": "image",2337                "data": base64.b64encode(image_bytes).decode('utf-8'),2338                "mime_type": "image/jpeg"2339            }2340        ],2341    )23422343    for step in interaction.steps:2344        if step.type == "model_output":2345            for content_block in step.content:2346                if content_block.type == "text":2347                    print(content_block.text)2348                elif content_block.type == "image":2349                    with open("comic_panel.jpg", "wb") as f:2350                        f.write(base64.b64decode(content_block.data))23512352### JavaScript23532354    import { GoogleGenAI } from "@google/genai";2355    import * as fs from "node:fs";23562357    async function main() {2358      const ai = new GoogleGenAI({});23592360      const imagePath = "/path/to/your/man_in_white_glasses.jpg";2361      const imageData = fs.readFileSync(imagePath);2362      const base64Image = imageData.toString("base64");23632364      const input = [2365        { 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." },2366        {2367          type: "image",2368          mime_type: "image/jpeg",2369          data: base64Image2370        },2371      ];23722373      const interaction = await ai.interactions.create({2374        model: "gemini-3.1-flash-image",2375        input: input,2376      });2377      for (const step of interaction.steps) {2378        if (step.type === "model_output") {2379          for (const contentBlock of step.content) {2380            if (contentBlock.type === "text") {2381              console.log(contentBlock.text);2382            } else if (contentBlock.type === "image") {2383              const buffer = Buffer.from(contentBlock.data, "base64");2384              fs.writeFileSync("comic_panel.jpg", buffer);2385            }2386          }2387        }2388      }2389    }23902391    main();23922393### Java23942395    import com.google.genai.Client;2396    import com.google.genai.gaos.models.interactions.Content;2397    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2398    import com.google.genai.gaos.models.interactions.ImageContent;2399    import com.google.genai.gaos.models.interactions.ImageContentMimeType;2400    import com.google.genai.gaos.models.interactions.Interaction;2401    import com.google.genai.gaos.models.interactions.InteractionsInput;2402    import com.google.genai.gaos.models.interactions.Model;2403    import com.google.genai.gaos.models.interactions.ModelOutputStep;2404    import com.google.genai.gaos.models.interactions.Step;2405    import com.google.genai.gaos.models.interactions.TextContent;2406    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2407    import java.nio.file.Files;2408    import java.nio.file.Paths;2409    import java.util.Arrays;2410    import java.util.Base64;2411    import java.util.List;24122413    Client client = new Client();24142415    byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/man_in_white_glasses.jpg"));2416    String base64Image = Base64.getEncoder().encodeToString(imageBytes);2417    String textInput =2418        "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.";24192420    Content textContent = TextContent.builder().text(textInput).build();2421    Content imageContent =2422        ImageContent.builder()2423            .data(base64Image)2424            .mimeType(ImageContentMimeType.IMAGE_JPEG)2425            .build();24262427    List<Content> contents = Arrays.asList(textContent, imageContent);24282429    CreateModelInteraction params =2430        CreateModelInteraction.builder()2431            .model(Model.of("gemini-3.1-flash-image"))2432            .input(InteractionsInput.ofContent(contents))2433            .build();24342435    Interaction interaction =2436        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();24372438    if (interaction.steps().isPresent()) {2439      for (Step step : interaction.steps().get()) {2440        if (step instanceof ModelOutputStep) {2441          ModelOutputStep outputStep = (ModelOutputStep) step;2442          if (outputStep.content().isPresent()) {2443            for (Content contentBlock : outputStep.content().get()) {2444              if (contentBlock instanceof TextContent) {2445                System.out.println(((TextContent) contentBlock).text().orElse(""));2446              } else if (contentBlock instanceof ImageContent) {2447                ImageContent img = (ImageContent) contentBlock;2448                if (img.data().isPresent()) {2449                  byte[] outBytes = Base64.getDecoder().decode(img.data().get());2450                  Files.write(Paths.get("comic_panel.jpg"), outBytes);2451                }2452              }2453            }2454          }2455        }2456      }2457    }24582459### REST24602461    curl -s -X POST \2462      "https://generativelanguage.googleapis.com/v1beta/interactions" \2463      -H "x-goog-api-key: $GEMINI_API_KEY" \2464      -H "Content-Type: application/json" \2465      -d '{2466        "model": "gemini-3.1-flash-image",2467        "input": [2468          {"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."},2469          {"type": "image", "data": "<BASE64_IMAGE_DATA>", "mime_type": "image/jpeg"}2470        ]2471      }'24722473|---|---|2474| Input | Output |2475| ![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... |24762477#### 7. Grounding with Google Search24782479Use Google Search to generate images based on recent or real-time information.2480This is useful for news, weather, and other time-sensitive topics.24812482### Prompt24832484    Make a simple but stylish graphic of last night's Arsenal game in the Champion's League24852486### Python24872488    from google import genai2489    from google.genai import types2490    import base6424912492    client = genai.Client()24932494    interaction = client.interactions.create(2495        model="gemini-3.1-flash-image",2496        input="Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",2497        tools=[{"type": "google_search"}],2498        response_format={"type": "image", "aspect_ratio": "16:9"},2499    )25002501    for step in interaction.steps:2502        if step.type == "model_output":2503            for content_block in step.content:2504                if content_block.type == "text":2505                    print(content_block.text)2506                elif content_block.type == "image":2507                    with open("football-score.jpg", "wb") as f:2508                        f.write(base64.b64decode(content_block.data))25092510### JavaScript25112512    import { GoogleGenAI } from "@google/genai";2513    import * as fs from "node:fs";25142515    async function main() {2516      const ai = new GoogleGenAI({});25172518      const interaction = await ai.interactions.create({2519        model: "gemini-3.1-flash-image",2520        input: "Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",2521        tools: [{ type: "google_search" }],2522        response_format: { type: "image", aspect_ratio: "16:9", image_size: "2K" },2523      });25242525      for (const step of interaction.steps) {2526        if (step.type === "model_output") {2527          for (const contentBlock of step.content) {2528            if (contentBlock.type === "text") {2529              console.log(contentBlock.text);2530            } else if (contentBlock.type === "image") {2531              const buffer = Buffer.from(contentBlock.data, "base64");2532              fs.writeFileSync("football-score.jpg", buffer);2533            }2534          }2535        }2536      }2537    }25382539    main();25402541### Java25422543    import com.google.genai.Client;2544    import com.google.genai.gaos.models.interactions.Content;2545    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2546    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;2547    import com.google.genai.gaos.models.interactions.GoogleSearch;2548    import com.google.genai.gaos.models.interactions.ImageContent;2549    import com.google.genai.gaos.models.interactions.ImageResponseFormat;2550    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;2551    import com.google.genai.gaos.models.interactions.Interaction;2552    import com.google.genai.gaos.models.interactions.InteractionsInput;2553    import com.google.genai.gaos.models.interactions.Model;2554    import com.google.genai.gaos.models.interactions.ModelOutputStep;2555    import com.google.genai.gaos.models.interactions.ResponseFormat;2556    import com.google.genai.gaos.models.interactions.Step;2557    import com.google.genai.gaos.models.interactions.TextContent;2558    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2559    import java.nio.file.Files;2560    import java.nio.file.Paths;2561    import java.util.Arrays;2562    import java.util.Base64;25632564    Client client = new Client();25652566    CreateModelInteractionResponseFormat format =2567        CreateModelInteractionResponseFormat.of(2568            ResponseFormat.of(2569                ImageResponseFormat.builder()2570                    .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))2571                    .build()));25722573    CreateModelInteraction params =2574        CreateModelInteraction.builder()2575            .model(Model.of("gemini-3.1-flash-image"))2576            .input(2577                InteractionsInput.of(2578                    "Make a simple but stylish graphic of last night's Arsenal game in the Champion's League"))2579            .tools(Arrays.asList(new GoogleSearch()))2580            .responseFormat(format)2581            .build();25822583    Interaction interaction =2584        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();25852586    if (interaction.steps().isPresent()) {2587      for (Step step : interaction.steps().get()) {2588        if (step instanceof ModelOutputStep) {2589          ModelOutputStep outputStep = (ModelOutputStep) step;2590          if (outputStep.content().isPresent()) {2591            for (Content contentBlock : outputStep.content().get()) {2592              if (contentBlock instanceof TextContent) {2593                System.out.println(((TextContent) contentBlock).text().orElse(""));2594              } else if (contentBlock instanceof ImageContent) {2595                ImageContent img = (ImageContent) contentBlock;2596                if (img.data().isPresent()) {2597                  byte[] imgBytes = Base64.getDecoder().decode(img.data().get());2598                  Files.write(Paths.get("football-score.jpg"), imgBytes);2599                }2600              }2601            }2602          }2603        }2604      }2605    }26062607### REST26082609    curl -s -X POST \2610      "https://generativelanguage.googleapis.com/v1beta/interactions" \2611      -H "x-goog-api-key: $GEMINI_API_KEY" \2612      -H "Content-Type: application/json" \2613      -d '{2614        "model": "gemini-3.1-flash-image",2615        "input": "Make a simple but stylish graphic of last nights Arsenal game in the Champions League",2616        "tools": [{"type": "google_search"}],2617        "response_format": {2618          "type": "image",2619          "aspect_ratio": "16:9"2620        }2621      }'26222623![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 score26242625### Prompts for editing images26262627These examples show how to provide images alongside your text prompts for2628editing, composition, and style transfer.26292630#### 1. Adding and removing elements26312632Provide an image and describe your change. The model will match the original2633image's style, lighting, and perspective.26342635### Template26362637    Using the provided image of [subject], please [add/remove/modify] [element]2638    to/from the scene. Ensure the change is [description of how the change should2639    integrate].26402641### Prompt26422643    "Using the provided image of my cat, please add a small, knitted wizard hat2644    on its head. Make it look like it's sitting comfortably and matches the soft2645    lighting of the photo."26462647### Python26482649    from google import genai2650    from PIL import Image2651    import base6426522653    client = genai.Client()26542655    with open('/path/to/your/cat_photo.png', 'rb') as f:2656        image_bytes = f.read()2657    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."""26582659    interaction = client.interactions.create(2660        model="gemini-3.1-flash-image",2661        input=[2662            {"type": "text", "text": text_input},2663            {2664                "type": "image",2665                "data": base64.b64encode(image_bytes).decode('utf-8'),2666                "mime_type": "image/png"2667            }2668        ],2669    )26702671    for step in interaction.steps:2672        if step.type == "model_output":2673            for content_block in step.content:2674                if content_block.type == "text":2675                    print(content_block.text)2676                elif content_block.type == "image":2677                    with open("cat_with_hat.png", "wb") as f:2678                        f.write(base64.b64decode(content_block.data))26792680### JavaScript26812682    import { GoogleGenAI } from "@google/genai";2683    import * as fs from "node:fs";26842685    async function main() {2686      const ai = new GoogleGenAI({});26872688      const imagePath = "/path/to/your/cat_photo.png";2689      const imageData = fs.readFileSync(imagePath);2690      const base64Image = imageData.toString("base64");26912692      const input = [2693        { 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." },2694        {2695          type: "image",2696          mime_type: "image/png",2697          data: base64Image2698        },2699      ];27002701      const interaction = await ai.interactions.create({2702        model: "gemini-3.1-flash-image",2703        input: input,2704      });2705      for (const step of interaction.steps) {2706        if (step.type === "model_output") {2707          for (const contentBlock of step.content) {2708            if (contentBlock.type === "text") {2709              console.log(contentBlock.text);2710            } else if (contentBlock.type === "image") {2711              const buffer = Buffer.from(contentBlock.data, "base64");2712              fs.writeFileSync("cat_with_hat.png", buffer);2713            }2714          }2715        }2716      }2717    }27182719    main();27202721### Java27222723    import com.google.genai.Client;2724    import com.google.genai.gaos.models.interactions.Content;2725    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2726    import com.google.genai.gaos.models.interactions.ImageContent;2727    import com.google.genai.gaos.models.interactions.ImageContentMimeType;2728    import com.google.genai.gaos.models.interactions.Interaction;2729    import com.google.genai.gaos.models.interactions.InteractionsInput;2730    import com.google.genai.gaos.models.interactions.Model;2731    import com.google.genai.gaos.models.interactions.ModelOutputStep;2732    import com.google.genai.gaos.models.interactions.Step;2733    import com.google.genai.gaos.models.interactions.TextContent;2734    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2735    import java.nio.file.Files;2736    import java.nio.file.Paths;2737    import java.util.Arrays;2738    import java.util.Base64;2739    import java.util.List;27402741    Client client = new Client();27422743    byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/cat_photo.png"));2744    String base64Image = Base64.getEncoder().encodeToString(imageBytes);2745    String textInput =2746        "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.";27472748    Content textContent = TextContent.builder().text(textInput).build();2749    Content imageContent =2750        ImageContent.builder()2751            .data(base64Image)2752            .mimeType(ImageContentMimeType.IMAGE_PNG)2753            .build();27542755    List<Content> contents = Arrays.asList(textContent, imageContent);27562757    CreateModelInteraction params =2758        CreateModelInteraction.builder()2759            .model(Model.of("gemini-3.1-flash-image"))2760            .input(InteractionsInput.ofContent(contents))2761            .build();27622763    Interaction interaction =2764        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();27652766    if (interaction.steps().isPresent()) {2767      for (Step step : interaction.steps().get()) {2768        if (step instanceof ModelOutputStep) {2769          ModelOutputStep outputStep = (ModelOutputStep) step;2770          if (outputStep.content().isPresent()) {2771            for (Content contentBlock : outputStep.content().get()) {2772              if (contentBlock instanceof TextContent) {2773                System.out.println(((TextContent) contentBlock).text().orElse(""));2774              } else if (contentBlock instanceof ImageContent) {2775                ImageContent img = (ImageContent) contentBlock;2776                if (img.data().isPresent()) {2777                  byte[] outBytes = Base64.getDecoder().decode(img.data().get());2778                  Files.write(Paths.get("cat_with_hat.png"), outBytes);2779                }2780              }2781            }2782          }2783        }2784      }2785    }27862787### REST27882789    curl -s -X POST \2790      "https://generativelanguage.googleapis.com/v1beta/interactions" \2791        -H "x-goog-api-key: $GEMINI_API_KEY" \2792        -H 'Content-Type: application/json' \2793        -d "{2794          \"model\": \"gemini-3.1-flash-image\",2795          \"input\": [2796                {\"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.\"},2797                {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"}2798            ]2799        }"28002801|---|---|2802| Input | Output |2803| :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... |28042805#### 2. Inpainting (semantic masking)28062807Conversationally define a "mask" to edit a specific part of an image while2808leaving the rest untouched.28092810### Template28112812    Using the provided image, change only the [specific element] to [new2813    element/description]. Keep everything else in the image exactly the same,2814    preserving the original style, lighting, and composition.28152816### Prompt28172818    "Using the provided image of a living room, change only the blue sofa to be2819    a vintage, brown leather chesterfield sofa. Keep the rest of the room,2820    including the pillows on the sofa and the lighting, unchanged."28212822### Python28232824    from google import genai2825    from PIL import Image2826    import base6428272828    client = genai.Client()28292830    with open('/path/to/your/living_room.png', 'rb') as f:2831        image_bytes = f.read()2832    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."""28332834    interaction = client.interactions.create(2835        model="gemini-3.1-flash-image",2836        input=[2837            {2838                "type": "image",2839                "data": base64.b64encode(image_bytes).decode('utf-8'),2840                "mime_type": "image/png"2841            },2842            {"type": "text", "text": text_input}2843        ],2844    )28452846    for step in interaction.steps:2847        if step.type == "model_output":2848            for content_block in step.content:2849                if content_block.type == "text":2850                    print(content_block.text)2851                elif content_block.type == "image":2852                    with open("living_room_edited.png", "wb") as f:2853                        f.write(base64.b64decode(content_block.data))28542855### JavaScript28562857    import { GoogleGenAI } from "@google/genai";2858    import * as fs from "node:fs";28592860    async function main() {2861      const ai = new GoogleGenAI({});28622863      const imagePath = "/path/to/your/living_room.png";2864      const imageData = fs.readFileSync(imagePath);2865      const base64Image = imageData.toString("base64");28662867      const input = [2868        {2869          type: "image",2870          mime_type: "image/png",2871          data: base64Image2872        },2873        { 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." },2874      ];28752876      const interaction = await ai.interactions.create({2877        model: "gemini-3.1-flash-image",2878        input: input,2879      });2880      for (const step of interaction.steps) {2881        if (step.type === "model_output") {2882          for (const contentBlock of step.content) {2883            if (contentBlock.type === "text") {2884              console.log(contentBlock.text);2885            } else if (contentBlock.type === "image") {2886              const buffer = Buffer.from(contentBlock.data, "base64");2887              fs.writeFileSync("living_room_edited.png", buffer);2888            }2889          }2890        }2891      }2892    }28932894    main();28952896### Java28972898    import com.google.genai.Client;2899    import com.google.genai.gaos.models.interactions.Content;2900    import com.google.genai.gaos.models.interactions.CreateModelInteraction;2901    import com.google.genai.gaos.models.interactions.ImageContent;2902    import com.google.genai.gaos.models.interactions.ImageContentMimeType;2903    import com.google.genai.gaos.models.interactions.Interaction;2904    import com.google.genai.gaos.models.interactions.InteractionsInput;2905    import com.google.genai.gaos.models.interactions.Model;2906    import com.google.genai.gaos.models.interactions.ModelOutputStep;2907    import com.google.genai.gaos.models.interactions.Step;2908    import com.google.genai.gaos.models.interactions.TextContent;2909    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;2910    import java.nio.file.Files;2911    import java.nio.file.Paths;2912    import java.util.Arrays;2913    import java.util.Base64;2914    import java.util.List;29152916    Client client = new Client();29172918    byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/living_room.png"));2919    String base64Image = Base64.getEncoder().encodeToString(imageBytes);2920    String textInput =2921        "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.";29222923    Content imageContent =2924        ImageContent.builder()2925            .data(base64Image)2926            .mimeType(ImageContentMimeType.IMAGE_PNG)2927            .build();2928    Content textContent = TextContent.builder().text(textInput).build();29292930    List<Content> contents = Arrays.asList(imageContent, textContent);29312932    CreateModelInteraction params =2933        CreateModelInteraction.builder()2934            .model(Model.of("gemini-3.1-flash-image"))2935            .input(InteractionsInput.ofContent(contents))2936            .build();29372938    Interaction interaction =2939        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();29402941    if (interaction.steps().isPresent()) {2942      for (Step step : interaction.steps().get()) {2943        if (step instanceof ModelOutputStep) {2944          ModelOutputStep outputStep = (ModelOutputStep) step;2945          if (outputStep.content().isPresent()) {2946            for (Content contentBlock : outputStep.content().get()) {2947              if (contentBlock instanceof TextContent) {2948                System.out.println(((TextContent) contentBlock).text().orElse(""));2949              } else if (contentBlock instanceof ImageContent) {2950                ImageContent img = (ImageContent) contentBlock;2951                if (img.data().isPresent()) {2952                  byte[] outBytes = Base64.getDecoder().decode(img.data().get());2953                  Files.write(Paths.get("living_room_edited.png"), outBytes);2954                }2955              }2956            }2957          }2958        }2959      }2960    }29612962### REST29632964    curl -s -X POST \2965      "https://generativelanguage.googleapis.com/v1beta/interactions" \2966        -H "x-goog-api-key: $GEMINI_API_KEY" \2967        -H 'Content-Type: application/json' \2968        -d "{2969          \"model\": \"gemini-3.1-flash-image\",2970          \"input\": [2971            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},2972            {\"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.\"}2973          ]2974        }"29752976|---|---|2977| Input | Output |2978| ![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... |29792980#### 3. Style transfer29812982Provide an image and ask the model to recreate its content in a different2983artistic style.29842985### Template29862987    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].29882989### Prompt29902991    "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."29922993### Python29942995    from google import genai2996    from PIL import Image2997    import base6429982999    client = genai.Client()30003001    with open('/path/to/your/city.png', 'rb') as f:3002        image_bytes = f.read()3003    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."""30043005    interaction = client.interactions.create(3006        model="gemini-3.1-flash-image",3007        input=[3008            {3009                "type": "image",3010                "data": base64.b64encode(image_bytes).decode('utf-8'),3011                "mime_type": "image/png"3012            },3013            {"type": "text", "text": text_input}3014        ],3015    )30163017    for step in interaction.steps:3018        if step.type == "model_output":3019            for content_block in step.content:3020                if content_block.type == "text":3021                    print(content_block.text)3022                elif content_block.type == "image":3023                    with open("city_style_transfer.png", "wb") as f:3024                        f.write(base64.b64decode(content_block.data))30253026### JavaScript30273028    import { GoogleGenAI } from "@google/genai";3029    import * as fs from "node:fs";30303031    async function main() {3032      const ai = new GoogleGenAI({});3033      const imageData = fs.readFileSync("/path/to/your/city.png");3034      const base64Image = imageData.toString("base64");30353036      const interaction = await ai.interactions.create({3037        model: "gemini-3.1-flash-image",3038        input: [3039          {3040            type: "image",3041            mime_type: "image/png",3042            data: base64Image3043          },3044          { 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." },3045        ],3046      });3047      for (const step of interaction.steps) {3048        if (step.type === "model_output") {3049          for (const contentBlock of step.content) {3050            if (contentBlock.type === "text") {3051              console.log(contentBlock.text);3052            } else if (contentBlock.type === "image") {3053              const buffer = Buffer.from(contentBlock.data, "base64");3054              fs.writeFileSync("city_style_transfer.png", buffer);3055            }3056          }3057        }3058      }3059    }30603061    main();30623063### Java30643065    import com.google.genai.Client;3066    import com.google.genai.gaos.models.interactions.Content;3067    import com.google.genai.gaos.models.interactions.CreateModelInteraction;3068    import com.google.genai.gaos.models.interactions.ImageContent;3069    import com.google.genai.gaos.models.interactions.ImageContentMimeType;3070    import com.google.genai.gaos.models.interactions.Interaction;3071    import com.google.genai.gaos.models.interactions.InteractionsInput;3072    import com.google.genai.gaos.models.interactions.Model;3073    import com.google.genai.gaos.models.interactions.ModelOutputStep;3074    import com.google.genai.gaos.models.interactions.Step;3075    import com.google.genai.gaos.models.interactions.TextContent;3076    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;3077    import java.nio.file.Files;3078    import java.nio.file.Paths;3079    import java.util.Arrays;3080    import java.util.Base64;3081    import java.util.List;30823083    Client client = new Client();30843085    byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/city.png"));3086    String base64Image = Base64.getEncoder().encodeToString(imageBytes);3087    String textInput =3088        "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.";30893090    Content imageContent =3091        ImageContent.builder()3092            .data(base64Image)3093            .mimeType(ImageContentMimeType.IMAGE_PNG)3094            .build();3095    Content textContent = TextContent.builder().text(textInput).build();30963097    List<Content> contents = Arrays.asList(imageContent, textContent);30983099    CreateModelInteraction params =3100        CreateModelInteraction.builder()3101            .model(Model.of("gemini-3.1-flash-image"))3102            .input(InteractionsInput.ofContent(contents))3103            .build();31043105    Interaction interaction =3106        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();31073108    if (interaction.steps().isPresent()) {3109      for (Step step : interaction.steps().get()) {3110        if (step instanceof ModelOutputStep) {3111          ModelOutputStep outputStep = (ModelOutputStep) step;3112          if (outputStep.content().isPresent()) {3113            for (Content contentBlock : outputStep.content().get()) {3114              if (contentBlock instanceof TextContent) {3115                System.out.println(((TextContent) contentBlock).text().orElse(""));3116              } else if (contentBlock instanceof ImageContent) {3117                ImageContent img = (ImageContent) contentBlock;3118                if (img.data().isPresent()) {3119                  byte[] outBytes = Base64.getDecoder().decode(img.data().get());3120                  Files.write(Paths.get("city_style_transfer.png"), outBytes);3121                }3122              }3123            }3124          }3125        }3126      }3127    }31283129### REST31303131    curl -s -X POST \3132      "https://generativelanguage.googleapis.com/v1beta/interactions" \3133        -H "x-goog-api-key: $GEMINI_API_KEY" \3134        -H 'Content-Type: application/json' \3135        -d "{3136          \"model\": \"gemini-3.1-flash-image\",3137          \"input\": [3138            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},3139            {\"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.\"}3140          ]3141        }"31423143|---|---|3144| Input | Output |3145| ![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... |31463147#### 4. Advanced composition: combining multiple images31483149Provide multiple images as context to create a new, composite scene. This is3150perfect for product mockups or creative collages.31513152### Template31533154    Create a new image by combining the elements from the provided images. Take3155    the [element from image 1] and place it with/on the [element from image 2].3156    The final image should be a [description of the final scene].31573158### Prompt31593160    "Create a professional e-commerce fashion photo. Take the blue floral dress3161    from the first image and let the woman from the second image wear it.3162    Generate a realistic, full-body shot of the woman wearing the dress, with3163    the lighting and shadows adjusted to match the outdoor environment."31643165### Python31663167    from google import genai3168    from PIL import Image3169    import base6431703171    client = genai.Client()31723173    with open('/path/to/your/dress.png', 'rb') as f:3174        dress_bytes = f.read()3175    with open('/path/to/your/model.png', 'rb') as f:3176        model_bytes = f.read()3177    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."""31783179    interaction = client.interactions.create(3180        model="gemini-3.1-flash-image",3181        input=[3182            {3183                "type": "image",3184                "data": base64.b64encode(dress_bytes).decode('utf-8'),3185                "mime_type": "image/png"3186            },3187            {3188                "type": "image",3189                "data": base64.b64encode(model_bytes).decode('utf-8'),3190                "mime_type": "image/png"3191            },3192            {"type": "text", "text": text_input}3193        ],3194    )31953196    for step in interaction.steps:3197        if step.type == "model_output":3198            for content_block in step.content:3199                if content_block.type == "text":3200                    print(content_block.text)3201                elif content_block.type == "image":3202                    with open("fashion_ecommerce_shot.png", "wb") as f:3203                        f.write(base64.b64decode(content_block.data))32043205### JavaScript32063207    import { GoogleGenAI } from "@google/genai";3208    import * as fs from "node:fs";32093210    async function main() {3211      const ai = new GoogleGenAI({});32123213      const imagePath1 = "/path/to/your/dress.png";3214      const imageData1 = fs.readFileSync(imagePath1);3215      const base64Image1 = imageData1.toString("base64");3216      const imagePath2 = "/path/to/your/model.png";3217      const imageData2 = fs.readFileSync(imagePath2);3218      const base64Image2 = imageData2.toString("base64");32193220      const input = [3221        {3222          type: "image",3223          mime_type: "image/png",3224          data: base64Image13225        },3226        {3227          type: "image",3228          mime_type: "image/png",3229          data: base64Image23230        },3231        { 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." },3232      ];32333234      const interaction = await ai.interactions.create({3235        model: "gemini-3.1-flash-image",3236        input: input,3237      });3238      for (const step of interaction.steps) {3239        if (step.type === "model_output") {3240          for (const contentBlock of step.content) {3241            if (contentBlock.type === "text") {3242              console.log(contentBlock.text);3243            } else if (contentBlock.type === "image") {3244              const buffer = Buffer.from(contentBlock.data, "base64");3245              fs.writeFileSync("fashion_ecommerce_shot.png", buffer);3246            }3247          }3248        }3249      }3250    }32513252    main();32533254### Java32553256    import com.google.genai.Client;3257    import com.google.genai.gaos.models.interactions.Content;3258    import com.google.genai.gaos.models.interactions.CreateModelInteraction;3259    import com.google.genai.gaos.models.interactions.ImageContent;3260    import com.google.genai.gaos.models.interactions.ImageContentMimeType;3261    import com.google.genai.gaos.models.interactions.Interaction;3262    import com.google.genai.gaos.models.interactions.InteractionsInput;3263    import com.google.genai.gaos.models.interactions.Model;3264    import com.google.genai.gaos.models.interactions.ModelOutputStep;3265    import com.google.genai.gaos.models.interactions.Step;3266    import com.google.genai.gaos.models.interactions.TextContent;3267    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;3268    import java.nio.file.Files;3269    import java.nio.file.Paths;3270    import java.util.Arrays;3271    import java.util.Base64;3272    import java.util.List;32733274    Client client = new Client();32753276    byte[] dressBytes = Files.readAllBytes(Paths.get("/path/to/your/dress.png"));3277    byte[] modelBytes = Files.readAllBytes(Paths.get("/path/to/your/model.png"));3278    String textInput =3279        "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.";32803281    Content dressContent =3282        ImageContent.builder()3283            .data(Base64.getEncoder().encodeToString(dressBytes))3284            .mimeType(ImageContentMimeType.IMAGE_PNG)3285            .build();3286    Content modelContent =3287        ImageContent.builder()3288            .data(Base64.getEncoder().encodeToString(modelBytes))3289            .mimeType(ImageContentMimeType.IMAGE_PNG)3290            .build();3291    Content textContent = TextContent.builder().text(textInput).build();32923293    List<Content> contents = Arrays.asList(dressContent, modelContent, textContent);32943295    CreateModelInteraction params =3296        CreateModelInteraction.builder()3297            .model(Model.of("gemini-3.1-flash-image"))3298            .input(InteractionsInput.ofContent(contents))3299            .build();33003301    Interaction interaction =3302        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();33033304    if (interaction.steps().isPresent()) {3305      for (Step step : interaction.steps().get()) {3306        if (step instanceof ModelOutputStep) {3307          ModelOutputStep outputStep = (ModelOutputStep) step;3308          if (outputStep.content().isPresent()) {3309            for (Content contentBlock : outputStep.content().get()) {3310              if (contentBlock instanceof TextContent) {3311                System.out.println(((TextContent) contentBlock).text().orElse(""));3312              } else if (contentBlock instanceof ImageContent) {3313                ImageContent img = (ImageContent) contentBlock;3314                if (img.data().isPresent()) {3315                  byte[] outBytes = Base64.getDecoder().decode(img.data().get());3316                  Files.write(Paths.get("fashion_ecommerce_shot.png"), outBytes);3317                }3318              }3319            }3320          }3321        }3322      }3323    }33243325### REST33263327    curl -s -X POST \3328      "https://generativelanguage.googleapis.com/v1beta/interactions" \3329        -H "x-goog-api-key: $GEMINI_API_KEY" \3330        -H 'Content-Type: application/json' \3331        -d "{3332          \"model\": \"gemini-3.1-flash-image\",3333          \"input\": [3334                {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_1>\"},3335                {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},3336                {\"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.\"}3337          }]3338        }"33393340|---|---|---|3341| Input 1 | Input 2 | Output |3342| :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 |33433344#### 5. High-fidelity detail preservation33453346To ensure critical details (like a face or logo) are preserved during an edit,3347describe them in great detail along with your edit request.33483349### Template33503351    Using the provided images, place [element from image 2] onto [element from3352    image 1]. Ensure that the features of [element from image 1] remain3353    completely unchanged. The added element should [description of how the3354    element should integrate].33553356### Prompt33573358    "Take the first image of the woman with brown hair, blue eyes, and a neutral3359    expression. Add the logo from the second image onto her black t-shirt.3360    Ensure the woman's face and features remain completely unchanged. The logo3361    should look like it's naturally printed on the fabric, following the folds3362    of the shirt."33633364### Python33653366    from google import genai3367    from PIL import Image3368    import base6433693370    client = genai.Client()33713372    with open('/path/to/your/woman.png', 'rb') as f:3373        woman_bytes = f.read()3374    with open('/path/to/your/logo.png', 'rb') as f:3375        logo_bytes = f.read()3376    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."""33773378    interaction = client.interactions.create(3379        model="gemini-3.1-flash-image",3380        input=[3381          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(woman_bytes).decode('utf-8')},3382          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(logo_bytes).decode('utf-8')},3383          {"type": "text", "text": text_input}3384        ],3385    )33863387    for step in interaction.steps:3388        if step.type == "model_output":3389            for content_block in step.content:3390                if content_block.type == "text":3391                    print(content_block.text)3392                elif content_block.type == "image":3393                    with open("woman_with_logo.png", "wb") as f:3394                        f.write(base64.b64decode(content_block.data))33953396### JavaScript33973398    import { GoogleGenAI } from "@google/genai";3399    import * as fs from "node:fs";34003401    async function main() {3402      const ai = new GoogleGenAI({});34033404      const imagePath1 = "/path/to/your/woman.png";3405      const imageData1 = fs.readFileSync(imagePath1);3406      const base64Image1 = imageData1.toString("base64");3407      const imagePath2 = "/path/to/your/logo.png";3408      const imageData2 = fs.readFileSync(imagePath2);3409      const base64Image2 = imageData2.toString("base64");34103411      const input = [3412        {"type": "image", "mime_type":"image/png", "data": base64Image1},3413        {"type": "image", "mime_type":"image/png", "data": base64Image2},3414        {"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."},3415      ];34163417      const interaction = await ai.interactions.create({3418        model: "gemini-3.1-flash-image",3419        input: input,3420      });3421      for (const step of interaction.steps) {3422        if (step.type === "model_output") {3423          for (const contentBlock of step.content) {3424            if (contentBlock.type === "text") {3425              console.log(contentBlock.text);3426            } else if (contentBlock.type === "image") {3427              const buffer = Buffer.from(contentBlock.data, "base64");3428              fs.writeFileSync("woman_with_logo.png", buffer);3429            }3430          }3431        }3432      }3433    }34343435    main();34363437### Java34383439    import com.google.genai.Client;3440    import com.google.genai.gaos.models.interactions.Content;3441    import com.google.genai.gaos.models.interactions.CreateModelInteraction;3442    import com.google.genai.gaos.models.interactions.ImageContent;3443    import com.google.genai.gaos.models.interactions.ImageContentMimeType;3444    import com.google.genai.gaos.models.interactions.Interaction;3445    import com.google.genai.gaos.models.interactions.InteractionsInput;3446    import com.google.genai.gaos.models.interactions.Model;3447    import com.google.genai.gaos.models.interactions.ModelOutputStep;3448    import com.google.genai.gaos.models.interactions.Step;3449    import com.google.genai.gaos.models.interactions.TextContent;3450    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;3451    import java.nio.file.Files;3452    import java.nio.file.Paths;3453    import java.util.Arrays;3454    import java.util.Base64;3455    import java.util.List;34563457    Client client = new Client();34583459    byte[] womanBytes = Files.readAllBytes(Paths.get("/path/to/your/woman.png"));3460    byte[] logoBytes = Files.readAllBytes(Paths.get("/path/to/your/logo.png"));3461    String textInput =3462        "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.";34633464    Content womanContent =3465        ImageContent.builder()3466            .data(Base64.getEncoder().encodeToString(womanBytes))3467            .mimeType(ImageContentMimeType.IMAGE_PNG)3468            .build();3469    Content logoContent =3470        ImageContent.builder()3471            .data(Base64.getEncoder().encodeToString(logoBytes))3472            .mimeType(ImageContentMimeType.IMAGE_PNG)3473            .build();3474    Content textContent = TextContent.builder().text(textInput).build();34753476    List<Content> contents = Arrays.asList(womanContent, logoContent, textContent);34773478    CreateModelInteraction params =3479        CreateModelInteraction.builder()3480            .model(Model.of("gemini-3.1-flash-image"))3481            .input(InteractionsInput.ofContent(contents))3482            .build();34833484    Interaction interaction =3485        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();34863487    if (interaction.steps().isPresent()) {3488      for (Step step : interaction.steps().get()) {3489        if (step instanceof ModelOutputStep) {3490          ModelOutputStep outputStep = (ModelOutputStep) step;3491          if (outputStep.content().isPresent()) {3492            for (Content contentBlock : outputStep.content().get()) {3493              if (contentBlock instanceof TextContent) {3494                System.out.println(((TextContent) contentBlock).text().orElse(""));3495              } else if (contentBlock instanceof ImageContent) {3496                ImageContent img = (ImageContent) contentBlock;3497                if (img.data().isPresent()) {3498                  byte[] outBytes = Base64.getDecoder().decode(img.data().get());3499                  Files.write(Paths.get("woman_with_logo.png"), outBytes);3500                }3501              }3502            }3503          }3504        }3505      }3506    }35073508### REST35093510    curl -s -X POST \3511      "https://generativelanguage.googleapis.com/v1beta/interactions" \3512        -H "x-goog-api-key: $GEMINI_API_KEY" \3513        -H 'Content-Type: application/json' \3514        -d "{3515          \"model\": \"gemini-3.1-flash-image\",3516          \"input\": [3517            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_1>\"},3518            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},3519            {\"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.\"}3520          ]3521        }"35223523|---|---|---|3524| Input 1 | Input 2 | Output |3525| :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... |35263527#### 6. Bring something to life35283529Upload a rough sketch or drawing and ask the model to refine it into a3530finished image.35313532### Template35333534    Turn this rough [medium] sketch of a [subject] into a [style description]3535    photo. Keep the [specific features] from the sketch but add [new details/materials].35363537### Prompt35383539    "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."35403541### Python35423543    from google import genai3544    from PIL import Image3545    import base6435463547    client = genai.Client()35483549    with open('/path/to/your/car_sketch.png', 'rb') as f:3550        sketch_bytes = f.read()3551    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."""35523553    interaction = client.interactions.create(3554        model="gemini-3.1-flash-image",3555        input=[3556          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(sketch_bytes).decode('utf-8')},3557          {"type": "text", "text": text_input}3558        ],3559    )35603561    for step in interaction.steps:3562        if step.type == "model_output":3563            for content_block in step.content:3564                if content_block.type == "text":3565                    print(content_block.text)3566                elif content_block.type == "image":3567                    with open("car_photo.png", "wb") as f:3568                        f.write(base64.b64decode(content_block.data))35693570### JavaScript35713572    import { GoogleGenAI } from "@google/genai";3573    import * as fs from "node:fs";35743575    async function main() {3576      const ai = new GoogleGenAI({});35773578      const imagePath = "/path/to/your/car_sketch.png";3579      const imageData = fs.readFileSync(imagePath);3580      const base64Image = imageData.toString("base64");35813582      const input = [3583        {"type": "image", "mime_type":"image/png", "data": base64Image},3584        {"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."},3585      ];35863587      const interaction = await ai.interactions.create({3588        model: "gemini-3.1-flash-image",3589        input: input,3590      });3591      for (const step of interaction.steps) {3592        if (step.type === "model_output") {3593          for (const contentBlock of step.content) {3594            if (contentBlock.type === "text") {3595              console.log(contentBlock.text);3596            } else if (contentBlock.type === "image") {3597              const buffer = Buffer.from(contentBlock.data, "base64");3598              fs.writeFileSync("car_photo.png", buffer);3599            }3600          }3601        }3602      }3603    }36043605    main();36063607### Java36083609    import com.google.genai.Client;3610    import com.google.genai.gaos.models.interactions.Content;3611    import com.google.genai.gaos.models.interactions.CreateModelInteraction;3612    import com.google.genai.gaos.models.interactions.ImageContent;3613    import com.google.genai.gaos.models.interactions.ImageContentMimeType;3614    import com.google.genai.gaos.models.interactions.Interaction;3615    import com.google.genai.gaos.models.interactions.InteractionsInput;3616    import com.google.genai.gaos.models.interactions.Model;3617    import com.google.genai.gaos.models.interactions.ModelOutputStep;3618    import com.google.genai.gaos.models.interactions.Step;3619    import com.google.genai.gaos.models.interactions.TextContent;3620    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;3621    import java.nio.file.Files;3622    import java.nio.file.Paths;3623    import java.util.Arrays;3624    import java.util.Base64;3625    import java.util.List;36263627    Client client = new Client();36283629    byte[] sketchBytes = Files.readAllBytes(Paths.get("/path/to/your/car_sketch.png"));3630    String textInput =3631        "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.";36323633    Content sketchContent =3634        ImageContent.builder()3635            .data(Base64.getEncoder().encodeToString(sketchBytes))3636            .mimeType(ImageContentMimeType.IMAGE_PNG)3637            .build();3638    Content textContent = TextContent.builder().text(textInput).build();36393640    List<Content> contents = Arrays.asList(sketchContent, textContent);36413642    CreateModelInteraction params =3643        CreateModelInteraction.builder()3644            .model(Model.of("gemini-3.1-flash-image"))3645            .input(InteractionsInput.ofContent(contents))3646            .build();36473648    Interaction interaction =3649        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();36503651    if (interaction.steps().isPresent()) {3652      for (Step step : interaction.steps().get()) {3653        if (step instanceof ModelOutputStep) {3654          ModelOutputStep outputStep = (ModelOutputStep) step;3655          if (outputStep.content().isPresent()) {3656            for (Content contentBlock : outputStep.content().get()) {3657              if (contentBlock instanceof TextContent) {3658                System.out.println(((TextContent) contentBlock).text().orElse(""));3659              } else if (contentBlock instanceof ImageContent) {3660                ImageContent img = (ImageContent) contentBlock;3661                if (img.data().isPresent()) {3662                  byte[] outBytes = Base64.getDecoder().decode(img.data().get());3663                  Files.write(Paths.get("car_photo.png"), outBytes);3664                }3665              }3666            }3667          }3668        }3669      }3670    }36713672### REST36733674    curl -s -X POST \3675      "https://generativelanguage.googleapis.com/v1beta/interactions" \3676        -H "x-goog-api-key: $GEMINI_API_KEY" \3677        -H 'Content-Type: application/json' \3678        -d "{3679          \"model\": \"gemini-3.1-flash-image\",3680          \"input\": [3681            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},3682            {\"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.\"}3683          ]3684        }"36853686|---|---|3687| Input | Output |3688| ![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 |36893690#### 7. Character consistency: 360 view36913692You can generate 360-degree views of a character by iteratively prompting for3693different angles. For best results, include previously generated images in3694subsequent prompts to maintain consistency. For complex poses, include a3695reference image of the selected pose.36963697### Template36983699    A studio portrait of [person] against [background], [looking forward/in profile looking right/etc.]37003701### Prompt37023703    A studio portrait of this man against white, in profile looking right37043705### Python37063707    from google import genai3708    from PIL import Image3709    import base6437103711    client = genai.Client()37123713    with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:3714        image_bytes = f.read()3715    text_input = """A studio portrait of this man against white, in profile looking right"""37163717    interaction = client.interactions.create(3718        model="gemini-3.1-flash-image",3719        input={3720          {"type": "text", "text": text_input},3721          {"type": "image", "mime_type":"image/png", "data": base64.b64encode(image_bytes).decode('utf-8')}3722        },3723    )37243725    for step in interaction.steps:3726        if step.type == "model_output":3727            for content_block in step.content:3728                if content_block.type == "text":3729                    print(content_block.text)3730                elif content_block.type == "image":3731                    with open("man_right_profile.png", "wb") as f:3732                        f.write(base64.b64decode(content_block.data))37333734|---|---|---|3735| Input | Output 1 | Output 2 |3736| ![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 |37373738### Best practices37393740To elevate your results from good to great, incorporate these professional3741strategies into your workflow.37423743- **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."3744- **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."3745- **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."3746- **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."3747- **Use "semantic negative prompts":** Instead of saying "no cars," describe the intended scene positively: "an empty, deserted street with no signs of traffic."3748- **Control the camera:** Use photographic and cinematic language to control the composition. Terms like `wide-angle shot`, `macro shot`, `low-angle3749  perspective`.37503751## Limitations37523753- 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.3754- Image generation does not support audio inputs. Video inputs are only supported for Gemini 3.1 Flash Image and Gemini 3.1 Flash Lite Image.3755- The model won't always follow the exact number of image outputs that the user explicitly asks for.3756- `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.3757- When generating text for an image, Gemini works best if you first generate the text and then ask for an image with the text.3758- `gemini-3.1-flash-image` Grounding with Google Search does not support using real-world images of people from web search at this time.3759- All generated images include a [SynthID watermark](https://ai.google.dev/responsible/docs/safeguards/synthid).37603761## Optional configurations37623763You can optionally configure the output format, aspect ratio, and image size using the `response_format` parameter.37643765### Output format37663767The 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.37683769To request multiple modalities (for example, both text and the generated image), pass an array of format entries to `response_format` instead.37703771### Python37723773    interaction = client.interactions.create(3774        model="gemini-3.1-flash-image",3775        input="Write a short poem about a starry night and generate an image of it.",3776        response_format=[3777            {"type": "text"},3778            {"type": "image"},3779        ],3780    )37813782### JavaScript37833784    const interaction = await ai.interactions.create({3785      model: "gemini-3.1-flash-image",3786      input: "Write a short poem about a starry night and generate an image of it.",3787      response_format: [3788        { type: "text" },3789        { type: "image" },3790      ],3791    });37923793### Java37943795    import com.google.genai.Client;3796    import com.google.genai.gaos.models.interactions.CreateModelInteraction;3797    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;3798    import com.google.genai.gaos.models.interactions.ImageResponseFormat;3799    import com.google.genai.gaos.models.interactions.Interaction;3800    import com.google.genai.gaos.models.interactions.InteractionsInput;3801    import com.google.genai.gaos.models.interactions.Model;3802    import com.google.genai.gaos.models.interactions.ResponseFormat;3803    import com.google.genai.gaos.models.interactions.TextResponseFormat;3804    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;3805    import java.util.Arrays;38063807    Client client = new Client();38083809    CreateModelInteractionResponseFormat format =3810        CreateModelInteractionResponseFormat.of(3811            Arrays.asList(3812                ResponseFormat.of(TextResponseFormat.builder().build()),3813                ResponseFormat.of(ImageResponseFormat.builder().build())));38143815    CreateModelInteraction params =3816        CreateModelInteraction.builder()3817            .model(Model.of("gemini-3.1-flash-image"))3818            .input(3819                InteractionsInput.of(3820                    "Write a short poem about a starry night and generate an image of it."))3821            .responseFormat(format)3822            .build();38233824    Interaction interaction =3825        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();38263827### REST38283829    curl -s -X POST \3830      "https://generativelanguage.googleapis.com/v1beta/interactions" \3831      -H "x-goog-api-key: $GEMINI_API_KEY" \3832      -H 'Content-Type: application/json' \3833      -d '{3834        "model": "gemini-3.1-flash-image",3835        "input": "Write a short poem about a starry night and generate an image of it.",3836        "response_format": [3837          { "type": "text" },3838          { "type": "image" }3839        ]3840      }'38413842### Aspect ratios and image size38433844By 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"`.38453846### Python38473848    interaction = client.interactions.create(3849        model="gemini-3.1-flash-image",3850        input=prompt,3851        response_format={3852            "type": "image",3853            "aspect_ratio": "16:9",3854            "image_size": "2K",3855        },3856    )38573858### JavaScript38593860    const interaction = await ai.interactions.create({3861        model: "gemini-3.1-flash-image",3862        input: prompt,3863        response_format: {3864          type: "image",3865          aspect_ratio: "16:9",3866          image_size: "2K",3867        },3868      });38693870### Java38713872    import com.google.genai.Client;3873    import com.google.genai.gaos.models.interactions.CreateModelInteraction;3874    import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;3875    import com.google.genai.gaos.models.interactions.ImageResponseFormat;3876    import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;3877    import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;3878    import com.google.genai.gaos.models.interactions.Interaction;3879    import com.google.genai.gaos.models.interactions.InteractionsInput;3880    import com.google.genai.gaos.models.interactions.Model;3881    import com.google.genai.gaos.models.interactions.ResponseFormat;3882    import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;38833884    Client client = new Client();3885    String prompt = "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";38863887    CreateModelInteractionResponseFormat format =3888        CreateModelInteractionResponseFormat.of(3889            ResponseFormat.of(3890                ImageResponseFormat.builder()3891                    .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))3892                    .imageSize(ImageResponseFormatImageSize.TWO_K)3893                    .build()));38943895    CreateModelInteraction params =3896        CreateModelInteraction.builder()3897            .model(Model.of("gemini-3.1-flash-image"))3898            .input(InteractionsInput.of(prompt))3899            .responseFormat(format)3900            .build();39013902    Interaction interaction =3903        client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();39043905### REST39063907    curl -s -X POST \3908      "https://generativelanguage.googleapis.com/v1beta/interactions" \3909      -H "x-goog-api-key: $GEMINI_API_KEY" \3910      -H 'Content-Type: application/json' \3911      -d '{3912        "model": "gemini-3.1-flash-image",3913        "input": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",3914        "response_format": {3915          "type": "image",3916          "aspect_ratio": "16:9",3917          "image_size": "2K"3918        }3919      }'39203921The different ratios available and the size of the image generated are listed in3922the following tables:39233924### 3.1 Flash Image39253926| Aspect ratio | 512px resolution | 0.5K tokens | 1K resolution | 1K tokens | 2K resolution | 2K tokens | 4K resolution | 4K tokens |3927|---|---|---|---|---|---|---|---|---|3928| **1:1** | 512x512 | 747 | 1024x1024 | 1120 | 2048x2048 | 1680 | 4096x4096 | 2520 |3929| **1:4** | 256x1024 | 747 | 512x2048 | 1120 | 1024x4096 | 1680 | 2048x8192 | 2520 |3930| **1:8** | 192x1536 | 747 | 384x3072 | 1120 | 768x6144 | 1680 | 1536x12288 | 2520 |3931| **2:3** | 424x632 | 747 | 848x1264 | 1120 | 1696x2528 | 1680 | 3392x5056 | 2520 |3932| **3:2** | 632x424 | 747 | 1264x848 | 1120 | 2528x1696 | 1680 | 5056x3392 | 2520 |3933| **3:4** | 448x600 | 747 | 896x1200 | 1120 | 1792x2400 | 1680 | 3584x4800 | 2520 |3934| **4:1** | 1024x256 | 747 | 2048x512 | 1120 | 4096x1024 | 1680 | 8192x2048 | 2520 |3935| **4:3** | 600x448 | 747 | 1200x896 | 1120 | 2400x1792 | 1680 | 4800x3584 | 2520 |3936| **4:5** | 464x576 | 747 | 928x1152 | 1120 | 1856x2304 | 1680 | 3712x4608 | 2520 |3937| **5:4** | 576x464 | 747 | 1152x928 | 1120 | 2304x1856 | 1680 | 4608x3712 | 2520 |3938| **8:1** | 1536x192 | 747 | 3072x384 | 1120 | 6144x768 | 1680 | 12288x1536 | 2520 |3939| **9:16** | 384x688 | 747 | 768x1376 | 1120 | 1536x2752 | 1680 | 3072x5504 | 2520 |3940| **16:9** | 688x384 | 747 | 1376x768 | 1120 | 2752x1536 | 1680 | 5504x3072 | 2520 |3941| **21:9** | 792x168 | 747 | 1584x672 | 1120 | 3168x1344 | 1680 | 6336x2688 | 2520 |39423943### 3.1 Pro Image39443945| Aspect ratio | 1K resolution | 1K tokens | 2K resolution | 2K tokens | 4K resolution | 4K tokens |3946|---|---|---|---|---|---|---|3947| **1:1** | 1024x1024 | 1120 | 2048x2048 | 1120 | 4096x4096 | 2000 |3948| **2:3** | 848x1264 | 1120 | 1696x2528 | 1120 | 3392x5056 | 2000 |3949| **3:2** | 1264x848 | 1120 | 2528x1696 | 1120 | 5056x3392 | 2000 |3950| **3:4** | 896x1200 | 1120 | 1792x2400 | 1120 | 3584x4800 | 2000 |3951| **4:3** | 1200x896 | 1120 | 2400x1792 | 1120 | 4800x3584 | 2000 |3952| **4:5** | 928x1152 | 1120 | 1856x2304 | 1120 | 3712x4608 | 2000 |3953| **5:4** | 1152x928 | 1120 | 2304x1856 | 1120 | 4608x3712 | 2000 |3954| **9:16** | 768x1376 | 1120 | 1536x2752 | 1120 | 3072x5504 | 2000 |3955| **16:9** | 1376x768 | 1120 | 2752x1536 | 1120 | 5504x3072 | 2000 |3956| **21:9** | 1584x672 | 1120 | 3168x1344 | 1120 | 6336x2688 | 2000 |39573958### Gemini 2.5 Flash Image39593960| Aspect ratio | Resolution | Tokens |3961|---|---|---|3962| 1:1 | 1024x1024 | 1290 |3963| 2:3 | 832x1248 | 1290 |3964| 3:2 | 1248x832 | 1290 |3965| 3:4 | 864x1184 | 1290 |3966| 4:3 | 1184x864 | 1290 |3967| 4:5 | 896x1152 | 1290 |3968| 5:4 | 1152x896 | 1290 |3969| 9:16 | 768x1344 | 1290 |3970| 16:9 | 1344x768 | 1290 |3971| 21:9 | 1536x672 | 1290 |39723973## Model selection39743975Choose the model best suited for your specific use case.39763977- **Gemini 3.1 Flash Image (Nano Banana 2)** should be your3978  go-to image generation model, as the best all around performance and3979  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 more3980  details.39813982- **Gemini 3.1 Flash Lite Image (Nano Banana 2 Lite)** is the most efficient3983  model in the image generation family, offering3984  ultra-low latency and cost-effective image generation and editing.3985  Check the model [pricing](https://ai.google.dev/gemini-api/docs/pricing#gemini-3.1-flash-lite-image)3986  and [capabilities](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-image) page3987  for more details.39883989- **Gemini 3 Pro Image (Nano Banana Pro)** is designed for3990  professional asset production and complex instructions. This model features3991  real-world grounding using Google Search, a default "Thinking" process that3992  refines composition prior to generation, and can generate images of up to 4K3993  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 more3994  details.39953996- **Gemini 2.5 Flash Image (Nano Banana)** is designed for speed and3997  efficiency. This model is optimized for high-volume, low-latency tasks and3998  generates images at 1024px resolution. Check the model [pricing](https://ai.google.dev/gemini-api/docs/pricing#gemini-2.5-flash-image) and3999  [capabilities](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image) page for more4000  details.40014002### When to use Imagen40034004> [!WARNING]4005> Imagen models are shut down. Use Nano Banana models for all image generation tasks.40064007Imagen is shut down and no longer available through the Gemini API.4008Use Nano Banana for image generation and editing.40094010## What's next40114012- Check out the [Veo guide](https://ai.google.dev/gemini-api/docs/video) to learn how to generate videos with the Gemini API.4013- To learn more about Gemini models, see [Gemini models](https://ai.google.dev/gemini-api/docs/models/gemini).
Files main
Menu

Theme