SPB Git

Repository Public

image-generation.md 120.4 KB 3,112 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- [Try a Nano Banana 2 app](https://aistudio.google.com/apps/bundled/pet_passport)6- Or build your own from prompts:7- ![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)8- ![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.   9  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." Create [professional product shots](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#4_product_mockups_commercial_photography) in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2)10- ![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." Learn more about [search grounding](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#use-with-grounding) and try it in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding)11- ![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." Use Google [Image Search](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#image-search) grounding with Nano Banana 2. Try it in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding)12- ![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." Try Nano Banana's [high fidelity detail preservation](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#5_high-fidelity_detail_preservation) in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2)13- ![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" Experiment with different [artistic styles](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#3_style_transfer) with Nano Banana in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2)14- ![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." Generate [accurate text](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#3_accurate_text_in_images) from [search](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#use-with-grounding). Try Nano Banana in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding)15- ![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." Create [icons, stickers, and assets](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#2_stylized_illustrations_stickers) with Nano Banana in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2,search_grounding)16- ![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." Try [photorealistic image generation](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#1_photorealistic_scenes) in [AI Studio](https://aistudio.google.com/apps?features=nano_banana_2)1718**Nano Banana** is the name for Gemini's native image generation capabilities.19Gemini can generate and process images conversationally20with text, images, video, or a combination. This lets you create, edit, and21iterate on visuals with unprecedented control.2223Nano Banana refers to four distinct models available in the Gemini API:2425- **Nano Banana 2 Lite ([Gemini 3.1 Flash Lite Image](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-image))26  (`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.27- **Nano Banana 2 ([Gemini 3.1 Flash Image](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-image))28  (`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.29- **Nano Banana Pro ([Gemini 3 Pro Image](https://ai.google.dev/gemini-api/docs/models/gemini-3-pro-image))30  (`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.31- **Nano Banana ([Gemini 2.5 Flash Image](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image))32  (`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.3334All generated images include a [SynthID watermark](https://ai.google.dev/responsible/docs/safeguards/synthid).3536## Image generation (text-to-image)3738### Python3940    from google import genai41    from google.genai import types42    from PIL import Image4344    client = genai.Client()4546    prompt = ("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme")47    response = client.models.generate_content(48        model="gemini-3.1-flash-image",49        contents=[prompt],50    )5152    for part in response.parts:53        if part.text is not None:54            print(part.text)55        elif part.inline_data is not None:56            image = part.as_image()57            image.save("generated_image.png")5859### JavaScript6061    import { GoogleGenAI } from "@google/genai";62    import * as fs from "node:fs";6364    async function main() {6566      const ai = new GoogleGenAI({});6768      const prompt =69        "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";7071      const response = await ai.models.generateContent({72        model: "gemini-3.1-flash-image",73        contents: prompt,74      });75      for (const part of response.candidates[0].content.parts) {76        if (part.text) {77          console.log(part.text);78        } else if (part.inlineData) {79          const imageData = part.inlineData.data;80          const buffer = Buffer.from(imageData, "base64");81          fs.writeFileSync("gemini-native-image.png", buffer);82          console.log("Image saved as gemini-native-image.png");83        }84      }85    }8687    main();8889### Go9091    package main9293    import (94      "context"95      "fmt"96      "log"97      "os"98      "google.golang.org/genai"99    )100101    func main() {102103      ctx := context.Background()104      client, err := genai.NewClient(ctx, nil)105      if err != nil {106          log.Fatal(err)107      }108109      result, _ := client.Models.GenerateContent(110          ctx,111          "gemini-3.1-flash-image",112          genai.Text("Create a picture of a nano banana dish in a " +113                     " fancy restaurant with a Gemini theme"),114      )115116      for _, part := range result.Candidates[0].Content.Parts {117          if part.Text != "" {118              fmt.Println(part.Text)119          } else if part.InlineData != nil {120              imageBytes := part.InlineData.Data121              outputFilename := "gemini_generated_image.png"122              _ = os.WriteFile(outputFilename, imageBytes, 0644)123          }124      }125    }126127### Java128129    import com.google.genai.Client;130    import com.google.genai.types.GenerateContentConfig;131    import com.google.genai.types.GenerateContentResponse;132    import com.google.genai.types.Part;133134    import java.io.IOException;135    import java.nio.file.Files;136    import java.nio.file.Paths;137138    public class TextToImage {139      public static void main(String[] args) throws IOException {140141        try (Client client = new Client()) {142          GenerateContentConfig config = GenerateContentConfig.builder()143              .responseModalities("TEXT", "IMAGE")144              .build();145146          GenerateContentResponse response = client.models.generateContent(147              "gemini-3.1-flash-image",148              "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",149              config);150151          for (Part part : response.parts()) {152            if (part.text().isPresent()) {153              System.out.println(part.text().get());154            } else if (part.inlineData().isPresent()) {155              var blob = part.inlineData().get();156              if (blob.data().isPresent()) {157                Files.write(Paths.get("_01_generated_image.png"), blob.data().get());158              }159            }160          }161        }162      }163    }164165### C#166167    using Google.GenAI;168    using System;169    using System.Collections.Generic;170    using System.IO;171    using System.Threading.Tasks;172173    public class TextToImage {174      public static async Task Main(string[] args) {175        var client = new Client();176177        var response = await client.Models.GenerateContentAsync(178            model: "gemini-3.1-flash-image",179            contents: new List<Part>180            {181                new Part { Text = "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme" }182            }183        );184185        foreach (var candidate in response.Candidates) {186            foreach (var part in candidate.Content.Parts) {187                if (part.Text != null) {188                    Console.WriteLine(part.Text);189                } else if (part.InlineData != null) {190                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);191                    await File.WriteAllBytesAsync("generated_image.png", imageBytes);192                    Console.WriteLine("Image saved as generated_image.png");193                }194            }195        }196      }197    }198199### REST200201    curl -s -X POST \202      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \203      -H "x-goog-api-key: $GEMINI_API_KEY" \204      -H "Content-Type: application/json" \205      -d '{206        "contents": [{207          "parts": [208            {"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}209          ]210        }]211      }'212213## Image editing (text-and-image-to-image)214215**Reminder** : Make sure you have the necessary rights to any images you upload.216Don't generate content that infringe on others' rights, including videos or217images that deceive, harass, or harm. Your use of this generative AI service is218subject to our [Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy).219220Provide an image and use text prompts to add, remove, or modify elements,221change the style, or adjust the color grading.222223The following example demonstrates uploading `base64` encoded images.224For multiple images, larger payloads, and supported MIME types, check the [Image225understanding](https://ai.google.dev/gemini-api/docs/image-understanding) page.226227### Python228229    from google import genai230    from google.genai import types231    from PIL import Image232233    client = genai.Client()234235    prompt = (236        "Create a picture of my cat eating a nano-banana in a "237        "fancy restaurant under the Gemini constellation",238    )239240    image = Image.open("/path/to/cat_image.png")241242    response = client.models.generate_content(243        model="gemini-3.1-flash-image",244        contents=[prompt, image],245    )246247    for part in response.parts:248        if part.text is not None:249            print(part.text)250        elif part.inline_data is not None:251            image = part.as_image()252            image.save("generated_image.png")253254### JavaScript255256    import { GoogleGenAI } from "@google/genai";257    import * as fs from "node:fs";258259    async function main() {260261      const ai = new GoogleGenAI({});262263      const imagePath = "path/to/cat_image.png";264      const imageData = fs.readFileSync(imagePath);265      const base64Image = imageData.toString("base64");266267      const prompt = [268        { text: "Create a picture of my cat eating a nano-banana in a" +269                "fancy restaurant under the Gemini constellation" },270        {271          inlineData: {272            mimeType: "image/png",273            data: base64Image,274          },275        },276      ];277278      const response = await ai.models.generateContent({279        model: "gemini-3.1-flash-image",280        contents: prompt,281      });282      for (const part of response.candidates[0].content.parts) {283        if (part.text) {284          console.log(part.text);285        } else if (part.inlineData) {286          const imageData = part.inlineData.data;287          const buffer = Buffer.from(imageData, "base64");288          fs.writeFileSync("gemini-native-image.png", buffer);289          console.log("Image saved as gemini-native-image.png");290        }291      }292    }293294    main();295296### Go297298    package main299300    import (301     "context"302     "fmt"303     "log"304     "os"305     "google.golang.org/genai"306    )307308    func main() {309310     ctx := context.Background()311     client, err := genai.NewClient(ctx, nil)312     if err != nil {313         log.Fatal(err)314     }315316     imagePath := "/path/to/cat_image.png"317     imgData, _ := os.ReadFile(imagePath)318319     parts := []*genai.Part{320       genai.NewPartFromText("Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation"),321       &genai.Part{322         InlineData: &genai.Blob{323           MIMEType: "image/png",324           Data:     imgData,325         },326       },327     }328329     contents := []*genai.Content{330       genai.NewContentFromParts(parts, genai.RoleUser),331     }332333     result, _ := client.Models.GenerateContent(334         ctx,335         "gemini-3.1-flash-image",336         contents,337     )338339     for _, part := range result.Candidates[0].Content.Parts {340         if part.Text != "" {341             fmt.Println(part.Text)342         } else if part.InlineData != nil {343             imageBytes := part.InlineData.Data344             outputFilename := "gemini_generated_image.png"345             _ = os.WriteFile(outputFilename, imageBytes, 0644)346         }347     }348    }349350### Java351352    import com.google.genai.Client;353    import com.google.genai.types.Content;354    import com.google.genai.types.GenerateContentConfig;355    import com.google.genai.types.GenerateContentResponse;356    import com.google.genai.types.Part;357358    import java.io.IOException;359    import java.nio.file.Files;360    import java.nio.file.Path;361    import java.nio.file.Paths;362363    public class TextAndImageToImage {364      public static void main(String[] args) throws IOException {365366        try (Client client = new Client()) {367          GenerateContentConfig config = GenerateContentConfig.builder()368              .responseModalities("TEXT", "IMAGE")369              .build();370371          GenerateContentResponse response = client.models.generateContent(372              "gemini-3.1-flash-image",373              Content.fromParts(374                  Part.fromText("""375                      Create a picture of my cat eating a nano-banana in376                      a fancy restaurant under the Gemini constellation377                      """),378                  Part.fromBytes(379                      Files.readAllBytes(380                          Path.of("src/main/resources/cat.jpg")),381                      "image/jpeg")),382              config);383384          for (Part part : response.parts()) {385            if (part.text().isPresent()) {386              System.out.println(part.text().get());387            } else if (part.inlineData().isPresent()) {388              var blob = part.inlineData().get();389              if (blob.data().isPresent()) {390                Files.write(Paths.get("gemini_generated_image.png"), blob.data().get());391              }392            }393          }394        }395      }396    }397398### C#399400    using Google.GenAI;401    using System;402    using System.Collections.Generic;403    using System.IO;404    using System.Threading.Tasks;405406    public class TextAndImageToImage {407      public static async Task Main(string[] args) {408        var client = new Client();409410        var response = await client.Models.GenerateContentAsync(411            model: "gemini-3.1-flash-image",412            contents: new List<Part>413            {414                new Part { Text = "Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation" },415                new Part416                {417                    FileData = new FileData { FileUri = "file:///path/to/cat_image.png" }418                }419            }420        );421422        foreach (var candidate in response.Candidates) {423            foreach (var part in candidate.Content.Parts) {424                if (part.Text != null) {425                    Console.WriteLine(part.Text);426                } else if (part.InlineData != null) {427                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);428                    await File.WriteAllBytesAsync("gemini_generated_image.png", imageBytes);429                    Console.WriteLine("Image saved as gemini_generated_image.png");430                }431            }432        }433      }434    }435436### REST437438    curl -s -X POST \439      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \440        -H "x-goog-api-key: $GEMINI_API_KEY" \441        -H 'Content-Type: application/json' \442        -d "{443          \"contents\": [{444            \"parts\":[445                {\"text\": \"'Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"},446                {447                  \"inline_data\": {448                    \"mime_type\":\"image/jpeg\",449                    \"data\": \"<BASE64_IMAGE_DATA>\"450                  }451                }452            ]453          }]454        }"455456### Multi-turn image editing457458Keep generating and editing images conversationally. Chat or multi-turn459conversation is the recommended way to iterate on images. The following460example shows a prompt to generate an infographic about photosynthesis.461462### Python463464    from google import genai465    from google.genai import types466467    client = genai.Client()468469    chat = client.chats.create(470        model="gemini-3.1-flash-image",471        config=types.GenerateContentConfig(472            response_modalities=['TEXT', 'IMAGE'],473            tools=[{"google_search": {}}]474        )475    )476477    message = "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."478479    response = chat.send_message(message)480481    for part in response.parts:482        if part.text is not None:483            print(part.text)484        elif image:= part.as_image():485            image.save("photosynthesis.png")486487### Javascript488489    import { GoogleGenAI } from "@google/genai";490491    const ai = new GoogleGenAI({});492493    async function main() {494      const chat = ai.chats.create({495        model: "gemini-3.1-flash-image",496        config: {497          responseModalities: ['TEXT', 'IMAGE'],498          tools: [{googleSearch: {}}],499        },500      });501    }502503    await main();504505    const message = "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."506507    let response = await chat.sendMessage({message});508509    for (const part of response.candidates[0].content.parts) {510        if (part.text) {511          console.log(part.text);512        } else if (part.inlineData) {513          const imageData = part.inlineData.data;514          const buffer = Buffer.from(imageData, "base64");515          fs.writeFileSync("photosynthesis.png", buffer);516          console.log("Image saved as photosynthesis.png");517        }518    }519520### Go521522    package main523524    import (525        "context"526        "fmt"527        "log"528        "os"529530        "google.golang.org/genai"531    )532533    func main() {534        ctx := context.Background()535        client, err := genai.NewClient(ctx, nil)536        if err != nil {537            log.Fatal(err)538        }539        defer client.Close()540541        model := client.GenerativeModel("gemini-3.1-flash-image")542        model.GenerationConfig = &pb.GenerationConfig{543            ResponseModalities: []pb.ResponseModality{genai.Text, genai.Image},544        }545        chat := model.StartChat()546547        message := "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."548549        resp, err := chat.SendMessage(ctx, genai.Text(message))550        if err != nil {551            log.Fatal(err)552        }553554        for _, part := range resp.Candidates[0].Content.Parts {555            if txt, ok := part.(genai.Text); ok {556                fmt.Printf("%s", string(txt))557            } else if img, ok := part.(genai.ImageData); ok {558                err := os.WriteFile("photosynthesis.png", img.Data, 0644)559                if err != nil {560                    log.Fatal(err)561                }562            }563        }564    }565566### Java567568    import com.google.genai.Chat;569    import com.google.genai.Client;570    import com.google.genai.types.Content;571    import com.google.genai.types.GenerateContentConfig;572    import com.google.genai.types.GenerateContentResponse;573    import com.google.genai.types.GoogleSearch;574    import com.google.genai.types.ImageConfig;575    import com.google.genai.types.Part;576    import com.google.genai.types.RetrievalConfig;577    import com.google.genai.types.Tool;578    import com.google.genai.types.ToolConfig;579580    import java.io.IOException;581    import java.nio.file.Files;582    import java.nio.file.Path;583    import java.nio.file.Paths;584585    public class MultiturnImageEditing {586      public static void main(String[] args) throws IOException {587588        try (Client client = new Client()) {589590          GenerateContentConfig config = GenerateContentConfig.builder()591              .responseModalities("TEXT", "IMAGE")592              .tools(Tool.builder()593                  .googleSearch(GoogleSearch.builder().build())594                  .build())595              .build();596597          Chat chat = client.chats.create("gemini-3.1-flash-image", config);598599          GenerateContentResponse response = chat.sendMessage("""600              Create a vibrant infographic that explains photosynthesis601              as if it were a recipe for a plant's favorite food.602              Show the "ingredients" (sunlight, water, CO2)603              and the "finished dish" (sugar/energy).604              The style should be like a page from a colorful605              kids' cookbook, suitable for a 4th grader.606              """);607608          for (Part part : response.parts()) {609            if (part.text().isPresent()) {610              System.out.println(part.text().get());611            } else if (part.inlineData().isPresent()) {612              var blob = part.inlineData().get();613              if (blob.data().isPresent()) {614                Files.write(Paths.get("photosynthesis.png"), blob.data().get());615              }616            }617          }618          // ...619        }620      }621    }622623### C#624625    using Google.GenAI;626    using System;627    using System.Collections.Generic;628    using System.IO;629    using System.Threading.Tasks;630631    public class MultiturnImageEditing {632      public static async Task Main(string[] args) {633        var client = new Client();634635        var response = await client.Models.GenerateContentAsync(636            model: "gemini-3.1-flash-image",637            contents: new List<Part>638            {639                new Part { Text = "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." }640            },641            config: new GenerateContentConfig642            {643                ResponseModalities = new List<string> { "TEXT", "IMAGE" },644                Tools = new List<Tool> { new Tool { GoogleSearch = new GoogleSearch() } }645            }646        );647648        foreach (var candidate in response.Candidates) {649            foreach (var part in candidate.Content.Parts) {650                if (part.Text != null) {651                    Console.WriteLine(part.Text);652                } else if (part.InlineData != null) {653                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);654                    await File.WriteAllBytesAsync("photosynthesis.png", imageBytes);655                    Console.WriteLine("Image saved as photosynthesis.png");656                }657            }658        }659      }660    }661662### REST663664    curl -s -X POST \665      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \666      -H "x-goog-api-key: $GEMINI_API_KEY" \667      -H "Content-Type: application/json" \668      -d '{669        "contents": [{670          "role": "user",671          "parts": [672            {"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."}673          ]674        }],675        "generationConfig": {676          "responseModalities": ["TEXT", "IMAGE"]677        }678      }'679680![AI-generated infographic about photosynthesis](https://ai.google.dev/static/gemini-api/docs/images/infographic-eng.png) AI-generated infographic about photosynthesis681682You can then use the same chat to change the language on the graphic to Spanish.683684### Python685686    message = "Update this infographic to be in Spanish. Do not change any other elements of the image."687    aspect_ratio = "16:9" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"688    resolution = "2K" # "512", "1K", "2K", "4K"689690    response = chat.send_message(message,691        config=types.GenerateContentConfig(692            response_format={"image": {aspect_ratio: aspect_ratio,                 image_size: resolution}},693        ))694695    for part in response.parts:696        if part.text is not None:697            print(part.text)698        elif image:= part.as_image():699            image.save("photosynthesis_spanish.png")700701### Javascript702703    const message = 'Update this infographic to be in Spanish. Do not change any other elements of the image.';704    const aspectRatio = '16:9';705    const resolution = '2K';706707    let response = await chat.sendMessage({708      message,709      config: {710        responseModalities: ['TEXT', 'IMAGE'],711        responseFormat: {712        image: {713          aspectRatio: aspectRatio,714          imageSize: resolution,715        }716      },717        tools: [{googleSearch: {}}],718      },719    });720721    for (const part of response.candidates[0].content.parts) {722        if (part.text) {723          console.log(part.text);724        } else if (part.inlineData) {725          const imageData = part.inlineData.data;726          const buffer = Buffer.from(imageData, "base64");727          fs.writeFileSync("photosynthesis2.png", buffer);728          console.log("Image saved as photosynthesis2.png");729        }730    }731732### Go733734    message = "Update this infographic to be in Spanish. Do not change any other elements of the image."735    aspect_ratio = "16:9" // "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"736    resolution = "2K"     // "512", "1K", "2K", "4K"737738    model.GenerationConfig.ImageConfig = &pb.ImageConfig{739        AspectRatio: aspect_ratio,740        ImageSize:   resolution,741    }742743    resp, err = chat.SendMessage(ctx, genai.Text(message))744    if err != nil {745        log.Fatal(err)746    }747748    for _, part := range resp.Candidates[0].Content.Parts {749        if txt, ok := part.(genai.Text); ok {750            fmt.Printf("%s", string(txt))751        } else if img, ok := part.(genai.ImageData); ok {752            err := os.WriteFile("photosynthesis_spanish.png", img.Data, 0644)753            if err != nil {754                log.Fatal(err)755            }756        }757    }758759### Java760761    String aspectRatio = "16:9"; // "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"762    String resolution = "2K"; // "512", "1K", "2K", "4K"763764    config = GenerateContentConfig.builder()765        .responseModalities("TEXT", "IMAGE")766        .imageConfig(ImageConfig.builder()767            .aspectRatio(aspectRatio)768            .imageSize(resolution)769            .build())770        .build();771772    response = chat.sendMessage(773        "Update this infographic to be in Spanish. " +774        "Do not change any other elements of the image.",775        config);776777    for (Part part : response.parts()) {778      if (part.text().isPresent()) {779        System.out.println(part.text().get());780      } else if (part.inlineData().isPresent()) {781        var blob = part.inlineData().get();782        if (blob.data().isPresent()) {783          Files.write(Paths.get("photosynthesis_spanish.png"), blob.data().get());784        }785      }786    }787788### C#789790    using Google.GenAI;791    using System;792    using System.Collections.Generic;793    using System.IO;794    using System.Threading.Tasks;795796    public class MultiturnImageEditingSpanish {797      public static async Task Main(string[] args) {798        var client = new Client();799800        var response = await client.Models.GenerateContentAsync(801            model: "gemini-3.1-flash-image",802            contents: new List<Part>803            {804                new Part { Text = "Update this infographic to be in Spanish. Do not change any other elements of the image." }805            },806            config: new GenerateContentConfig807            {808                ResponseModalities = new List<string> { "TEXT", "IMAGE" },809                ImageConfig = new ImageConfig810                {811                    AspectRatio = "16:9",812                    ImageSize = "2K"813                }814            }815        );816817        foreach (var candidate in response.Candidates) {818            foreach (var part in candidate.Content.Parts) {819                if (part.Text != null) {820                    Console.WriteLine(part.Text);821                } else if (part.InlineData != null) {822                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);823                    await File.WriteAllBytesAsync("photosynthesis_spanish.png", imageBytes);824                    Console.WriteLine("Image saved as photosynthesis_spanish.png");825                }826            }827        }828      }829    }830831### REST832833    curl -s -X POST \834      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \835      -H "x-goog-api-key: $GEMINI_API_KEY" \836      -H 'Content-Type: application/json' \837      -d '{838        "contents": [839          {840            "role": "user",841            "parts": [{"text": "Create a vibrant infographic that explains photosynthesis..."}]842          },843          {844            "role": "model",845            "parts": [{"inline_data": {"mime_type": "image/png", "data": "<PREVIOUS_IMAGE_DATA>"}}]846          },847          {848            "role": "user",849            "parts": [{"text": "Update this infographic to be in Spanish. Do not change any other elements of the image."}]850          }851        ],852        "tools": [{"google_search": {}}],853        "generationConfig": {854          "responseModalities": ["TEXT", "IMAGE"],855          "responseFormat": {856        "image": {857            "aspectRatio": "16:9",858            "imageSize": "2K"859          }860      }861        }862      }'863864![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 Spanish865866## New with Gemini 3 image models867868Gemini 3 offers state-of-the-art image generation and editing models. Gemini 3.1869Flash Image is optimized for speed and high-volume use-cases, and Gemini 3870Pro Image is optimized for professional asset production.871Designed to tackle the most challenging workflows through advanced reasoning,872they excel at complex, multi-turn creation and modification tasks.873874- **High-resolution output** : Built-in generation capabilities for 1K, 2K, and 4K visuals.875  - **Gemini 3.1 Flash Image** adds the smaller 512 (0.5K) resolution.876  - **Gemini 3.1 Flash Lite Image** only supports 1K resolution.877- **Advanced text rendering**: Capable of generating legible, stylized text for infographics, menus, diagrams, and marketing assets.878- **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).879  - **Not supported by Gemini 3.1 Flash Lite Image model.**880  - **Gemini 3.1 Flash Image** adds the integration of Grounding with Google Search for Images alongside Web Search.881- **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.882- **Up to 14 reference images**: You can now mix up to 14 reference images to produce the final image.883- **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/generate-content/image-generation#aspect_ratios_and_image_size).884885### Use up to 14 reference images886887Gemini 3 image models let you to mix up to 14 reference images. These 14 images888can include the following:889890| Gemini 3.1 Flash Lite Image | Gemini 3.1 Flash Image | Gemini 3 Pro Image |891|---|---|---|892| 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 |893| N/A | Up to 4 images of characters to maintain character consistency | Up to 5 images of characters to maintain character consistency |894| N/A | N/A | Up to 3 images to be used as style references |895896### Python897898    from google import genai899    from google.genai import types900    from PIL import Image901902    prompt = "An office group photo of these people, they are making funny faces."903    aspect_ratio = "5:4" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"904    resolution = "2K" # "512", "1K", "2K", "4K"905906    client = genai.Client()907908    response = client.models.generate_content(909        model="gemini-3.1-flash-image",910        contents=[911            prompt,912            Image.open('person1.png'),913            Image.open('person2.png'),914            Image.open('person3.png'),915            Image.open('person4.png'),916            Image.open('person5.png'),917        ],918        config=types.GenerateContentConfig(919            response_modalities=['TEXT', 'IMAGE'],920            response_format={"image": {aspect_ratio: aspect_ratio,                 image_size: resolution}},921        )922    )923924    for part in response.parts:925        if part.text is not None:926            print(part.text)927        elif image:= part.as_image():928            image.save("office.png")929930### Javascript931932    import { GoogleGenAI } from "@google/genai";933    import * as fs from "node:fs";934935    async function main() {936937      const ai = new GoogleGenAI({});938939      const prompt =940          'An office group photo of these people, they are making funny faces.';941      const aspectRatio = '5:4';942      const resolution = '2K';943944    const contents = [945      { text: prompt },946      {947        inlineData: {948          mimeType: "image/jpeg",949          data: base64ImageFile1,950        },951      },952      {953        inlineData: {954          mimeType: "image/jpeg",955          data: base64ImageFile2,956        },957      },958      {959        inlineData: {960          mimeType: "image/jpeg",961          data: base64ImageFile3,962        },963      },964      {965        inlineData: {966          mimeType: "image/jpeg",967          data: base64ImageFile4,968        },969      },970      {971        inlineData: {972          mimeType: "image/jpeg",973          data: base64ImageFile5,974        },975      }976    ];977978    const response = await ai.models.generateContent({979        model: 'gemini-3.1-flash-image',980        contents: contents,981        config: {982          responseModalities: ['TEXT', 'IMAGE'],983          responseFormat: {984        image: {985            aspectRatio: aspectRatio,986            imageSize: resolution,987          }988      },989        },990      });991992      for (const part of response.candidates[0].content.parts) {993        if (part.text) {994          console.log(part.text);995        } else if (part.inlineData) {996          const imageData = part.inlineData.data;997          const buffer = Buffer.from(imageData, "base64");998          fs.writeFileSync("image.png", buffer);999          console.log("Image saved as image.png");1000        }1001      }10021003    }10041005    main();10061007### Go10081009    package main10101011    import (1012        "context"1013        "fmt"1014        "log"1015        "os"10161017        "google.golang.org/genai"1018    )10191020    func main() {1021        ctx := context.Background()1022        client, err := genai.NewClient(ctx, nil)1023        if err != nil {1024            log.Fatal(err)1025        }1026        defer client.Close()10271028        model := client.GenerativeModel("gemini-3.1-flash-image")1029        model.GenerationConfig = &pb.GenerationConfig{1030            ResponseModalities: []pb.ResponseModality{genai.Text, genai.Image},1031            ImageConfig: &pb.ImageConfig{1032                AspectRatio: "5:4",1033                ImageSize:   "2K",1034            },1035        }10361037        img1, err := os.ReadFile("person1.png")1038        if err != nil { log.Fatal(err) }1039        img2, err := os.ReadFile("person2.png")1040        if err != nil { log.Fatal(err) }1041        img3, err := os.ReadFile("person3.png")1042        if err != nil { log.Fatal(err) }1043        img4, err := os.ReadFile("person4.png")1044        if err != nil { log.Fatal(err) }1045        img5, err := os.ReadFile("person5.png")1046        if err != nil { log.Fatal(err) }10471048        parts := []genai.Part{1049            genai.Text("An office group photo of these people, they are making funny faces."),1050            genai.ImageData{MIMEType: "image/png", Data: img1},1051            genai.ImageData{MIMEType: "image/png", Data: img2},1052            genai.ImageData{MIMEType: "image/png", Data: img3},1053            genai.ImageData{MIMEType: "image/png", Data: img4},1054            genai.ImageData{MIMEType: "image/png", Data: img5},1055        }10561057        resp, err := model.GenerateContent(ctx, parts...)1058        if err != nil {1059            log.Fatal(err)1060        }10611062        for _, part := range resp.Candidates[0].Content.Parts {1063            if txt, ok := part.(genai.Text); ok {1064                fmt.Printf("%s", string(txt))1065            } else if img, ok := part.(genai.ImageData); ok {1066                err := os.WriteFile("office.png", img.Data, 0644)1067                if err != nil {1068                    log.Fatal(err)1069                }1070            }1071        }1072    }10731074### Java10751076    import com.google.genai.Client;1077    import com.google.genai.types.Content;1078    import com.google.genai.types.GenerateContentConfig;1079    import com.google.genai.types.GenerateContentResponse;1080    import com.google.genai.types.ImageConfig;1081    import com.google.genai.types.Part;10821083    import java.io.IOException;1084    import java.nio.file.Files;1085    import java.nio.file.Path;1086    import java.nio.file.Paths;10871088    public class GroupPhoto {1089      public static void main(String[] args) throws IOException {10901091        try (Client client = new Client()) {1092          GenerateContentConfig config = GenerateContentConfig.builder()1093              .responseModalities("TEXT", "IMAGE")1094              .imageConfig(ImageConfig.builder()1095                  .aspectRatio("5:4")1096                  .imageSize("2K")1097                  .build())1098              .build();10991100          GenerateContentResponse response = client.models.generateContent(1101              "gemini-3.1-flash-image",1102              Content.fromParts(1103                  Part.fromText("An office group photo of these people, they are making funny faces."),1104                  Part.fromBytes(Files.readAllBytes(Path.of("person1.png")), "image/png"),1105                  Part.fromBytes(Files.readAllBytes(Path.of("person2.png")), "image/png"),1106                  Part.fromBytes(Files.readAllBytes(Path.of("person3.png")), "image/png"),1107                  Part.fromBytes(Files.readAllBytes(Path.of("person4.png")), "image/png"),1108                  Part.fromBytes(Files.readAllBytes(Path.of("person5.png")), "image/png")1109              ), config);11101111          for (Part part : response.parts()) {1112            if (part.text().isPresent()) {1113              System.out.println(part.text().get());1114            } else if (part.inlineData().isPresent()) {1115              var blob = part.inlineData().get();1116              if (blob.data().isPresent()) {1117                Files.write(Paths.get("office.png"), blob.data().get());1118              }1119            }1120          }1121        }1122      }1123    }11241125### C#11261127    using Google.GenAI;1128    using System;1129    using System.Collections.Generic;1130    using System.IO;1131    using System.Threading.Tasks;11321133    public class GroupPhoto {1134      public static async Task Main(string[] args) {1135        var client = new Client();11361137        var response = await client.Models.GenerateContentAsync(1138            model: "gemini-3.1-flash-image",1139            contents: new List<Part>1140            {1141                new Part { Text = "An office group photo of these people, they are making funny faces." },1142                new Part { FileData = new FileData { FileUri = "file:///person1.png" } },1143                new Part { FileData = new FileData { FileUri = "file:///person2.png" } },1144                new Part { FileData = new FileData { FileUri = "file:///person3.png" } },1145                new Part { FileData = new FileData { FileUri = "file:///person4.png" } },1146                new Part { FileData = new FileData { FileUri = "file:///person5.png" } }1147            },1148            config: new GenerateContentConfig1149            {1150                ResponseModalities = new List<string> { "TEXT", "IMAGE" },1151                ImageConfig = new ImageConfig1152                {1153                    AspectRatio = "5:4",1154                    ImageSize = "2K"1155                }1156            }1157        );11581159        foreach (var candidate in response.Candidates) {1160            foreach (var part in candidate.Content.Parts) {1161                if (part.Text != null) {1162                    Console.WriteLine(part.Text);1163                } else if (part.InlineData != null) {1164                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);1165                    await File.WriteAllBytesAsync("office.png", imageBytes);1166                    Console.WriteLine("Image saved as office.png");1167                }1168            }1169        }1170      }1171    }11721173### REST11741175    curl -s -X POST \1176      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \1177        -H "x-goog-api-key: $GEMINI_API_KEY" \1178        -H 'Content-Type: application/json' \1179        -d "{1180          \"contents\": [{1181            \"parts\":[1182                {\"text\": \"An office group photo of these people, they are making funny faces.\"},1183                {\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_1>\"}},1184                {\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_2>\"}},1185                {\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_3>\"}},1186                {\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_4>\"}},1187                {\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_5>\"}}1188            ]1189          }],1190          \"generationConfig\": {1191            \"responseModalities\": [\"TEXT\", \"IMAGE\"],1192            \"responseFormat\": {1193            \"image\": {1194              \"aspectRatio\": \"5:4\",1195              \"imageSize\": \"2K\"1196            }1197          }1198          }1199        }"12001201![AI-generated office group photo](https://ai.google.dev/static/gemini-api/docs/images/office-group-photo.jpeg) AI-generated office group photo12021203### Grounding with Google Search12041205Use the [Google Search tool](https://ai.google.dev/gemini-api/docs/google-search) to generate images1206based on real-time information, such as weather forecasts, stock charts, or1207recent events.12081209Note that when using Grounding with Google Search with image generation,1210image-based search results are not passed to the generation model and are1211excluded from the response (see [Grounding with Google Search for images](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#image-search))12121213> [!NOTE]1214> **Note:** Grounding with Google Search is not supported by `gemini-3.1-flash-lite-image` model.12151216### Python12171218    from google import genai1219    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"1220    aspect_ratio = "16:9" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"12211222    client = genai.Client()12231224    response = client.models.generate_content(1225        model="gemini-3.1-flash-image",1226        contents=prompt,1227        config=types.GenerateContentConfig(1228            response_modalities=['Text', 'Image'],1229            response_format={"image": {aspect_ratio: aspect_ratio,}},1230            tools=[{"google_search": {}}]1231        )1232    )12331234    for part in response.parts:1235        if part.text is not None:1236            print(part.text)1237        elif image:= part.as_image():1238            image.save("weather.png")12391240### Javascript12411242    import { GoogleGenAI } from "@google/genai";1243    import * as fs from "node:fs";12441245    async function main() {12461247      const ai = new GoogleGenAI({});12481249      const 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';1250      const aspectRatio = '16:9';1251      const resolution = '2K';12521253    const response = await ai.models.generateContent({1254        model: 'gemini-3.1-flash-image',1255        contents: prompt,1256        config: {1257          responseModalities: ['TEXT', 'IMAGE'],1258          responseFormat: {1259        image: {1260            aspectRatio: aspectRatio,1261            imageSize: resolution,1262          }1263      },1264        tools: [{ googleSearch: {} }]1265        },1266      });12671268      for (const part of response.candidates[0].content.parts) {1269        if (part.text) {1270          console.log(part.text);1271        } else if (part.inlineData) {1272          const imageData = part.inlineData.data;1273          const buffer = Buffer.from(imageData, "base64");1274          fs.writeFileSync("image.png", buffer);1275          console.log("Image saved as image.png");1276        }1277      }12781279    }12801281    main();12821283### Java12841285    import com.google.genai.Client;1286    import com.google.genai.types.GenerateContentConfig;1287    import com.google.genai.types.GenerateContentResponse;1288    import com.google.genai.types.GoogleSearch;1289    import com.google.genai.types.ImageConfig;1290    import com.google.genai.types.Part;1291    import com.google.genai.types.Tool;12921293    import java.io.IOException;1294    import java.nio.file.Files;1295    import java.nio.file.Paths;12961297    public class SearchGrounding {1298      public static void main(String[] args) throws IOException {12991300        try (Client client = new Client()) {1301          GenerateContentConfig config = GenerateContentConfig.builder()1302              .responseModalities("TEXT", "IMAGE")1303              .imageConfig(ImageConfig.builder()1304                  .aspectRatio("16:9")1305                  .build())1306              .tools(Tool.builder()1307                  .googleSearch(GoogleSearch.builder().build())1308                  .build())1309              .build();13101311          GenerateContentResponse response = client.models.generateContent(1312              "gemini-3.1-flash-image", """1313                  Visualize the current weather forecast for the next 5 days1314                  in San Francisco as a clean, modern weather chart.1315                  Add a visual on what I should wear each day1316                  """,1317              config);13181319          for (Part part : response.parts()) {1320            if (part.text().isPresent()) {1321              System.out.println(part.text().get());1322            } else if (part.inlineData().isPresent()) {1323              var blob = part.inlineData().get();1324              if (blob.data().isPresent()) {1325                Files.write(Paths.get("weather.png"), blob.data().get());1326              }1327            }1328          }1329        }1330      }1331    }13321333### C#13341335    using Google.GenAI;1336    using System;1337    using System.Collections.Generic;1338    using System.IO;1339    using System.Threading.Tasks;13401341    public class SearchGrounding {1342      public static async Task Main(string[] args) {1343        var client = new Client();13441345        var response = await client.Models.GenerateContentAsync(1346            model: "gemini-3.1-flash-image",1347            contents: new List<Part>1348            {1349                new Part { 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" }1350            },1351            config: new GenerateContentConfig1352            {1353                ResponseModalities = new List<string> { "TEXT", "IMAGE" },1354                ImageConfig = new ImageConfig1355                {1356                    AspectRatio = "16:9"1357                },1358                Tools = new List<Tool> { new Tool { GoogleSearch = new GoogleSearch() } }1359            }1360        );13611362        foreach (var candidate in response.Candidates) {1363            foreach (var part in candidate.Content.Parts) {1364                if (part.Text != null) {1365                    Console.WriteLine(part.Text);1366                } else if (part.InlineData != null) {1367                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);1368                    await File.WriteAllBytesAsync("weather.png", imageBytes);1369                    Console.WriteLine("Image saved as weather.png");1370                }1371            }1372        }1373      }1374    }13751376### REST13771378    curl -s -X POST \1379      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \1380      -H "x-goog-api-key: $GEMINI_API_KEY" \1381      -H "Content-Type: application/json" \1382      -d '{1383        "contents": [{"parts": [{"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"}]}],1384        "tools": [{"google_search": {}}],1385        "generationConfig": {1386          "responseModalities": ["TEXT", "IMAGE"],1387          "responseFormat": {1388        "image": {"aspectRatio": "16:9"}1389      }1390        }1391      }'13921393![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 Francisco13941395The response includes `groundingMetadata` which contains the following required1396fields:13971398- **`searchEntryPoint`**: Contains the HTML and CSS to render the required search suggestions.1399- **`groundingChunks`**: Returns the top 3 web sources used to ground the generated image14001401### Grounding with Google Search for images (3.1 Flash)14021403> [!NOTE]1404> **Note:** This feature is only available for the Gemini 3.1 Flash Image model.14051406Grounding with Google Search for images allows models to use web images retrieved via1407Google Search as visual context for image generation. Image Search is a1408new search type within the existing Grounding with Google Search tool,1409functioning alongside standard [Web Search](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#use-with-grounding).14101411To enable Image Search, configure the `googleSearch` tool in your API request1412and specify `imageSearch` within the `searchTypes` object. Image Search can be1413used independently or together with Web Search.14141415Note that Grounding with Google Search for images can't be used to search for people.14161417### Python14181419    from google import genai1420    prompt = "A detailed painting of a Timareta butterfly resting on a flower"14211422    client = genai.Client()14231424    response = client.models.generate_content(1425        model="gemini-3.1-flash-image",1426        contents=prompt,1427        config=types.GenerateContentConfig(1428            response_modalities=["IMAGE"],1429            tools=[1430                types.Tool(google_search=types.GoogleSearch(1431                    search_types=types.SearchTypes(1432                        web_search=types.WebSearch(),1433                        image_search=types.ImageSearch()1434                    )1435                ))1436            ]1437        )1438    )14391440    # Display grounding sources if available1441    if response.candidates and response.candidates[0].grounding_metadata and response.candidates[0].grounding_metadata.search_entry_point:1442        display(HTML(response.candidates[0].grounding_metadata.search_entry_point.rendered_content))14431444### JavaScript14451446    import { GoogleGenAI } from "@google/genai";14471448    async function main() {14491450      const ai = new GoogleGenAI({});14511452      const prompt = "A detailed painting of a Timareta butterfly resting on a flower";14531454      const response = await ai.models.generateContent({1455        model: "gemini-3.1-flash-image",1456        contents: prompt,1457        config: {1458          responseModalities: ["IMAGE"],1459          tools: [1460            {1461              googleSearch: {1462                searchTypes: {1463                  webSearch: {},1464                  imageSearch: {}1465                }1466              }1467            }1468          ]1469        }1470      });14711472      // Display grounding sources if available1473      if (response.candidates && response.candidates[0].groundingMetadata && response.candidates[0].groundingMetadata.searchEntryPoint) {1474          console.log(response.candidates[0].groundingMetadata.searchEntryPoint.renderedContent);1475      }1476    }14771478    main();14791480### Go14811482    package main14831484    import (1485      "context"1486      "fmt"1487      "log"14881489      "google.golang.org/genai"1490      pb "google.golang.org/genai/schema"1491    )14921493    func main() {1494      ctx := context.Background()1495      client, err := genai.NewClient(ctx, nil)1496      if err != nil {1497        log.Fatal(err)1498      }1499      defer client.Close()15001501      model := client.GenerativeModel("gemini-3.1-flash-image")1502      model.Tools = []*pb.Tool{1503        {1504          GoogleSearch: &pb.GoogleSearch{1505            SearchTypes: &pb.SearchTypes{1506              WebSearch:   &pb.WebSearch{},1507              ImageSearch: &pb.ImageSearch{},1508            },1509          },1510        },1511      }1512      model.GenerationConfig = &pb.GenerationConfig{1513        ResponseModalities: []pb.ResponseModality{genai.Image},1514      }15151516      prompt := "A detailed painting of a Timareta butterfly resting on a flower"1517      resp, err := model.GenerateContent(ctx, genai.Text(prompt))1518      if err != nil {1519        log.Fatal(err)1520      }15211522      if resp.Candidates[0].GroundingMetadata != nil && resp.Candidates[0].GroundingMetadata.SearchEntryPoint != nil {1523        fmt.Println(resp.Candidates[0].GroundingMetadata.SearchEntryPoint.RenderedContent)1524      }1525    }15261527### Java15281529    import com.google.genai.Client;1530    import com.google.genai.types.GenerateContentConfig;1531    import com.google.genai.types.GenerateContentResponse;1532    import com.google.genai.types.GoogleSearch;1533    import com.google.genai.types.ImageSearch;1534    import com.google.genai.types.SearchTypes;1535    import com.google.genai.types.Tool;1536    import com.google.genai.types.WebSearch;15371538    import java.io.IOException;15391540    public class ImageSearchGrounding {1541      public static void main(String[] args) throws IOException {15421543        try (Client client = new Client()) {1544          GenerateContentConfig config = GenerateContentConfig.builder()1545              .responseModalities("IMAGE")1546              .tools(Tool.builder()1547                  .googleSearch(GoogleSearch.builder()1548                      .searchTypes(SearchTypes.builder()1549                          .webSearch(WebSearch.builder().build())1550                          .imageSearch(ImageSearch.builder().build())1551                          .build())1552                      .build())1553                  .build())1554              .build();15551556          GenerateContentResponse response = client.models.generateContent(1557              "gemini-3.1-flash-image",1558              "A detailed painting of a Timareta butterfly resting on a flower",1559              config);15601561          if (response.candidates().isPresent() && !response.candidates().get().isEmpty()) {1562            var candidate = response.candidates().get().get(0);1563            if (candidate.groundingMetadata().isPresent() && candidate.groundingMetadata().get().searchEntryPoint().isPresent()) {1564              System.out.println(candidate.groundingMetadata().get().searchEntryPoint().get().renderedContent().orElse(""));1565            }1566          }1567        }1568      }1569    }15701571### C#15721573    using Google.GenAI;1574    using System;1575    using System.Collections.Generic;1576    using System.Threading.Tasks;15771578    public class ImageSearchGrounding {1579      public static async Task Main(string[] args) {1580        var client = new Client();15811582        var response = await client.Models.GenerateContentAsync(1583            model: "gemini-3.1-flash-image",1584            contents: new List<Part>1585            {1586                new Part { Text = "A detailed painting of a Timareta butterfly resting on a flower" }1587            },1588            config: new GenerateContentConfig1589            {1590                ResponseModalities = new List<string> { "IMAGE" },1591                Tools = new List<Tool>1592                {1593                    new Tool1594                    {1595                        GoogleSearch = new GoogleSearch1596                        {1597                            SearchTypes = new SearchTypes1598                            {1599                                WebSearch = new WebSearch(),1600                                ImageSearch = new ImageSearch()1601                            }1602                        }1603                    }1604                }1605            }1606        );16071608        foreach (var candidate in response.Candidates) {1609            if (candidate.GroundingMetadata != null && candidate.GroundingMetadata.SearchEntryPoint != null) {1610                Console.WriteLine(candidate.GroundingMetadata.SearchEntryPoint.RenderedContent);1611            }1612        }1613      }1614    }16151616### REST16171618    curl -s -X POST \1619      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \1620      -H "x-goog-api-key: $GEMINI_API_KEY" \1621      -H "Content-Type: application/json" \1622      -d '{1623        "contents": [{"parts": [{"text": "A detailed painting of a Timareta butterfly resting on a flower"}]}],1624        "tools": [{"google_search": {"searchTypes": {"webSearch": {}, "imageSearch": {}}}}],1625        "generationConfig": {1626          "responseModalities": ["IMAGE"]1627        }1628      }'16291630**Display requirements**16311632When you use Image Search within Grounding with Google Search, you must comply1633with the following conditions:16341635- **Source attribution**: You must provide a link to the webpage containing the source image (the "containing page," not the image file itself) in a manner that the user will recognize as a link.1636- **Direct navigation**: If you also choose to display the source images, you must provide a direct, single-click path from the source images to its containing source webpage. Any other implementation that delays or abstracts the end user's access to the source webpage, including but not limited to any multi-click path or the use of an intermediate image viewer, is not permitted.16371638**Response**16391640For grounded responses using image search, the API provides clear attribution1641and metadata to link its output to verified sources. Key fields in the1642`groundingMetadata` object include:16431644- **`imageSearchQueries`**: The specific queries used by the model for visual context (image search).1645- **`groundingChunks`**: Contains source information for retrieved results.1646  For image sources, these will be returned as redirect URLs using a new image1647  chunk type. This chunk includes:16481649  - **`uri`**: The web page URL for attribution (the landing page).1650  - **`image_uri`**: The direct image URL.1651- **`groundingSupports`**: Provides specific mappings that link the generated1652  content to its relevant citation source in the chunks.16531654- **`searchEntryPoint`**: Includes the "Google Search" chip containing1655  compliant HTML and CSS to render Search Suggestions.16561657### Video-to-image generation (3.1 Flash and 3.1 Flash Lite)16581659> [!NOTE]1660> **Note:** This feature is only available for the Gemini 3.1 Flash Image and Gemini 3.1 Flash Lite Image models.16611662Video-to-image generation allows you to generate new images using a video's context1663as a multimodal reference. This is useful for creating high-quality video thumbnails, cinematic1664posters, summary infographics, or new artwork inspired by a video scene.16651666During generation, the model analyzes the video frames in context (up to the model's input token1667limit of 131,072 tokens) to extract visual themes and key events, then uses them alongside your text1668prompt to synthesize the output image.16691670You can pass public [YouTube URLs](https://ai.google.dev/gemini-api/docs/video-understanding#youtube)1671directly in your API request or upload local video files using the1672[Files API](https://ai.google.dev/gemini-api/docs/files).16731674### Python16751676    from google import genai1677    from google.genai import types16781679    client = genai.Client()16801681    # Pass a public YouTube video URL as part of the contents1682    response = client.models.generate_content(1683        model="gemini-3.1-flash-image",1684        contents=[1685            types.Part(1686              file_data=types.FileData(file_uri="https://www.youtube.com/watch?v=UTdfxFyOQTI"),1687              video_metadata=types.VideoMetadata(fps=0.5)1688            ),1689            "Generate a poster image that captures the key themes of this video."1690        ],1691        config=types.GenerateContentConfig(1692            response_modalities=["TEXT", "IMAGE"]1693        )1694    )16951696    # Save the generated image part1697    for part in response.parts:1698        if part.inline_data is not None:1699            image = part.as_image()1700            image.save("video_poster.png")1701            print("Image saved as video_poster.png")17021703### JavaScript17041705    import { GoogleGenAI } from "@google/genai";1706    import * as fs from "node:fs";17071708    async function main() {1709      const ai = new GoogleGenAI({});17101711      const response = await ai.models.generateContent({1712        model: "gemini-3.1-flash-image",1713        contents: [1714          {1715            fileData: {1716              fileUri: "https://www.youtube.com/watch?v=UTdfxFyOQTI",1717            },1718            videoMetadata: {1719              fps: 0.51720            }1721          },1722          { text: "Generate a poster image that captures the key themes of this video." }1723        ],1724        config: {1725          responseModalities: ["TEXT", "IMAGE"]1726        }1727      });17281729      for (const part of response.candidates[0].content.parts) {1730        if (part.inlineData) {1731          const imageData = part.inlineData.data;1732          const buffer = Buffer.from(imageData, "base64");1733          fs.writeFileSync("video_poster.png", buffer);1734          console.log("Image saved as video_poster.png");1735        }1736      }1737    }17381739    main();17401741### Go17421743    package main17441745    import (1746        "context"1747        "log"1748        "os"1749        "google.golang.org/genai"1750    )17511752    func main() {1753        ctx := context.Background()1754        client, err := genai.NewClient(ctx, nil)1755        if err != nil {1756            log.Fatal(err)1757        }17581759        videoPart := genai.NewPartFromURI("https://www.youtube.com/watch?v=UTdfxFyOQTI", "video/mp4")1760        videoPart.VideoMetadata = &genai.VideoMetadata{FPS: genai.Ptr(0.5)}17611762        parts := []*genai.Part{1763            videoPart,1764            genai.NewPartFromText("Generate a poster image that captures the key themes of this video."),1765        }17661767        contents := []*genai.Content{1768            genai.NewContentFromParts(parts, genai.RoleUser),1769        }17701771        result, err := client.Models.GenerateContent(1772            ctx,1773            "gemini-3.1-flash-image",1774            contents,1775            &genai.GenerateContentConfig{1776                ResponseModalities: []string{"TEXT", "IMAGE"},1777            },1778        )1779        if err != nil {1780            log.Fatal(err)1781        }17821783        for _, part := range result.Candidates[0].Content.Parts {1784            if part.InlineData != nil {1785                imageBytes := part.InlineData.Data1786                _ = os.WriteFile("video_poster.png", imageBytes, 0644)1787                log.Println("Image saved as video_poster.png")1788            }1789        }1790    }17911792### Java17931794    import com.google.genai.Client;1795    import com.google.genai.types.Content;1796    import com.google.genai.types.FileData;1797    import com.google.genai.types.GenerateContentConfig;1798    import com.google.genai.types.GenerateContentResponse;1799    import com.google.genai.types.Part;1800    import com.google.genai.types.VideoMetadata;1801    import com.google.common.collect.ImmutableList;18021803    import java.io.IOException;1804    import java.nio.file.Files;1805    import java.nio.file.Paths;18061807    public class VideoToImage {1808      public static void main(String[] args) throws IOException {18091810        try (Client client = new Client()) {1811          Part videoPart = Part.builder()1812              .fileData(FileData.builder()1813                  .fileUri("https://www.youtube.com/watch?v=UTdfxFyOQTI")1814                  .build())1815              .videoMetadata(VideoMetadata.builder()1816                  .fps(0.5)1817                  .build())1818              .build();18191820          Part textPart = Part.builder()1821              .text("Generate a poster image that captures the key themes of this video.")1822              .build();18231824          GenerateContentConfig config = GenerateContentConfig.builder()1825              .responseModalities("TEXT", "IMAGE")1826              .build();18271828          GenerateContentResponse response = client.models.generateContent(1829              "gemini-3.1-flash-image",1830              Content.builder()1831                  .role("user")1832                  .parts(ImmutableList.of(videoPart, textPart))1833                  .build(),1834              config);18351836          for (Part part : response.parts()) {1837            if (part.inlineData().isPresent()) {1838              var blob = part.inlineData().get();1839              if (blob.data().isPresent()) {1840                Files.write(Paths.get("video_poster.png"), blob.data().get());1841                System.out.println("Image saved as video_poster.png");1842              }1843            }1844          }1845        }1846      }1847    }18481849### C#18501851    using Google.GenAI;1852    using Google.GenAI.Types;1853    using System;1854    using System.Collections.Generic;1855    using System.IO;1856    using System.Threading.Tasks;18571858    public class VideoToImage {1859      public static async Task Main(string[] args) {1860        var client = new Client();18611862        var response = await client.Models.GenerateContentAsync(1863            model: "gemini-3.1-flash-image",1864            contents: new List<Part>1865            {1866                new Part1867                {1868                    FileData = new FileData { FileUri = "https://www.youtube.com/watch?v=UTdfxFyOQTI" },1869                    VideoMetadata = new VideoMetadata { Fps = 0.5 }1870                },1871                new Part { Text = "Generate a poster image that captures the key themes of this video." }1872            },1873            config: new GenerateContentConfig1874            {1875                ResponseModalities = new List<string> { "TEXT", "IMAGE" }1876            }1877        );18781879        foreach (var candidate in response.Candidates) {1880            foreach (var part in candidate.Content.Parts) {1881                if (part.InlineData != null) {1882                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);1883                    await File.WriteAllBytesAsync("video_poster.png", imageBytes);1884                    Console.WriteLine("Image saved as video_poster.png");1885                }1886            }1887        }1888      }1889    }18901891### REST18921893    curl -s -X POST \1894      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \1895      -H "x-goog-api-key: $GEMINI_API_KEY" \1896      -H "Content-Type: application/json" \1897      -d '{1898        "contents": [{1899          "parts": [1900            {1901              "file_data": {1902                "file_uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI"1903              },1904              "video_metadata": {1905                "fps": 0.51906              }1907            },1908            {"text": "Generate a poster image that captures the key themes of this video."}1909          ]1910        }],1911        "generationConfig": {1912          "responseModalities": ["TEXT", "IMAGE"]1913        }1914      }'19151916![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 video19171918### Generate images up to 4K resolution19191920Gemini 3 image models generate 1K images by default but can also output 2K,19214K, and 512 (0.5K) (Gemini 3.1 Flash Image only) images. To generate higher1922resolution assets, specify the `image_size` in the `generation_config`.19231924> [!NOTE]1925> **Note:** **Gemini 3.1 Flash Lite image model** only supports 1K images.19261927You must use an uppercase 'K' (e.g. 1K, 2K, 4K). The `512` value does not use a 'K' suffix. Lowercase1928parameters (e.g., 1k) will be rejected.19291930### Python19311932    from google import genai1933    from google.genai import types19341935    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."1936    aspect_ratio = "1:1" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"1937    resolution = "1K" # "512", "1K", "2K", "4K"19381939    client = genai.Client()19401941    response = client.models.generate_content(1942        model="gemini-3.1-flash-image",1943        contents=prompt,1944        config=types.GenerateContentConfig(1945            response_modalities=['TEXT', 'IMAGE'],1946            response_format={"image": {aspect_ratio: aspect_ratio,                 image_size: resolution}},1947        )1948    )19491950    for part in response.parts:1951        if part.text is not None:1952            print(part.text)1953        elif image:= part.as_image():1954            image.save("butterfly.png")19551956### Javascript19571958    import { GoogleGenAI } from "@google/genai";1959    import * as fs from "node:fs";19601961    async function main() {19621963      const ai = new GoogleGenAI({});19641965      const prompt =1966          '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.';1967      const aspectRatio = '1:1';1968      const resolution = '1K';19691970      const response = await ai.models.generateContent({1971        model: 'gemini-3.1-flash-image',1972        contents: prompt,1973        config: {1974          responseModalities: ['TEXT', 'IMAGE'],1975          responseFormat: {1976        image: {1977            aspectRatio: aspectRatio,1978            imageSize: resolution,1979          }1980      },1981        },1982      });19831984      for (const part of response.candidates[0].content.parts) {1985        if (part.text) {1986          console.log(part.text);1987        } else if (part.inlineData) {1988          const imageData = part.inlineData.data;1989          const buffer = Buffer.from(imageData, "base64");1990          fs.writeFileSync("image.png", buffer);1991          console.log("Image saved as image.png");1992        }1993      }19941995    }19961997    main();19981999### Go20002001    package main20022003    import (2004        "context"2005        "fmt"2006        "log"2007        "os"20082009        "google.golang.org/genai"2010    )20112012    func main() {2013        ctx := context.Background()2014        client, err := genai.NewClient(ctx, nil)2015        if err != nil {2016            log.Fatal(err)2017        }2018        defer client.Close()20192020        model := client.GenerativeModel("gemini-3.1-flash-image")2021        model.GenerationConfig = &pb.GenerationConfig{2022            ResponseModalities: []pb.ResponseModality{genai.Text, genai.Image},2023            ImageConfig: &pb.ImageConfig{2024                AspectRatio: "1:1",2025                ImageSize:   "1K",2026            },2027        }20282029        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."2030        resp, err := model.GenerateContent(ctx, genai.Text(prompt))2031        if err != nil {2032            log.Fatal(err)2033        }20342035        for _, part := range resp.Candidates[0].Content.Parts {2036            if txt, ok := part.(genai.Text); ok {2037                fmt.Printf("%s", string(txt))2038            } else if img, ok := part.(genai.ImageData); ok {2039                err := os.WriteFile("butterfly.png", img.Data, 0644)2040                if err != nil {2041                    log.Fatal(err)2042                }2043            }2044        }2045    }20462047### Java20482049    import com.google.genai.Client;2050    import com.google.genai.types.GenerateContentConfig;2051    import com.google.genai.types.GenerateContentResponse;2052    import com.google.genai.types.GoogleSearch;2053    import com.google.genai.types.ImageConfig;2054    import com.google.genai.types.Part;2055    import com.google.genai.types.Tool;20562057    import java.io.IOException;2058    import java.nio.file.Files;2059    import java.nio.file.Paths;20602061    public class HiRes {2062        public static void main(String[] args) throws IOException {20632064          try (Client client = new Client()) {2065            GenerateContentConfig config = GenerateContentConfig.builder()2066                .responseModalities("TEXT", "IMAGE")2067                .imageConfig(ImageConfig.builder()2068                    .aspectRatio("16:9")2069                    .imageSize("4K")2070                    .build())2071                .build();20722073            GenerateContentResponse response = client.models.generateContent(2074                "gemini-3.1-flash-image", """2075                  Da Vinci style anatomical sketch of a dissected Monarch butterfly.2076                  Detailed drawings of the head, wings, and legs on textured2077                  parchment with notes in English.2078                  """,2079                config);20802081            for (Part part : response.parts()) {2082              if (part.text().isPresent()) {2083                System.out.println(part.text().get());2084              } else if (part.inlineData().isPresent()) {2085                var blob = part.inlineData().get();2086                if (blob.data().isPresent()) {2087                  Files.write(Paths.get("butterfly.png"), blob.data().get());2088                }2089              }2090            }2091          }2092        }2093    }20942095### C#20962097    using Google.GenAI;2098    using System;2099    using System.Collections.Generic;2100    using System.IO;2101    using System.Threading.Tasks;21022103    public class HiRes {2104      public static async Task Main(string[] args) {2105        var client = new Client();21062107        var response = await client.Models.GenerateContentAsync(2108            model: "gemini-3.1-flash-image",2109            contents: new List<Part>2110            {2111                new Part { Text = "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." }2112            },2113            config: new GenerateContentConfig2114            {2115                ResponseModalities = new List<string> { "TEXT", "IMAGE" },2116                ImageConfig = new ImageConfig2117                {2118                    AspectRatio = "1:1",2119                    ImageSize = "1K"2120                }2121            }2122        );21232124        foreach (var candidate in response.Candidates) {2125            foreach (var part in candidate.Content.Parts) {2126                if (part.Text != null) {2127                    Console.WriteLine(part.Text);2128                } else if (part.InlineData != null) {2129                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);2130                    await File.WriteAllBytesAsync("butterfly.png", imageBytes);2131                    Console.WriteLine("Image saved as butterfly.png");2132                }2133            }2134        }2135      }2136    }21372138### REST21392140    curl -s -X POST \2141      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \2142      -H "x-goog-api-key: $GEMINI_API_KEY" \2143      -H "Content-Type: application/json" \2144      -d '{2145        "contents": [{"parts": [{"text": "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."}]}],2146        "tools": [{"google_search": {}}],2147        "generationConfig": {2148          "responseModalities": ["TEXT", "IMAGE"],2149          "responseFormat": {2150        "image": {"aspectRatio": "1:1", "imageSize": "1K"}2151      }2152        }2153      }'21542155The following is an example image generated from this prompt:2156![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.21572158### Thinking process21592160Gemini 3 image models are thinking models that use a reasoning2161process ("Thinking") for complex prompts. This feature is enabled by default and2162cannot be disabled in the API. To learn more about the thinking process, see2163the [Gemini Thinking](https://ai.google.dev/gemini-api/docs/thinking) guide.21642165The model generates up to two interim images to test composition and logic. The2166last image within Thinking is also the final rendered image.21672168You can check the thoughts that lead to the final image being produced.21692170### Python21712172    for part in response.parts:2173        if part.thought:2174            if part.text:2175                print(part.text)2176            elif image:= part.as_image():2177                image.show()21782179### Javascript21802181    for (const part of response.candidates[0].content.parts) {2182      if (part.thought) {2183        if (part.text) {2184          console.log(part.text);2185        } else if (part.inlineData) {2186          const imageData = part.inlineData.data;2187          const buffer = Buffer.from(imageData, 'base64');2188          fs.writeFileSync('image.png', buffer);2189          console.log('Image saved as image.png');2190        }2191      }2192    }21932194### Java21952196    for (Part part : response.parts()) {2197      if (part.thought().orElse(false)) {2198        if (part.text().isPresent()) {2199          System.out.println(part.text().get());2200        } else if (part.inlineData().isPresent()) {2201          var blob = part.inlineData().get();2202          if (blob.data().isPresent()) {2203            Files.write(Paths.get("image.png"), blob.data().get());2204            System.out.println("Image saved as image.png");2205          }2206        }2207      }2208    }22092210### C#22112212    foreach (var candidate in response.Candidates) {2213        foreach (var part in candidate.Content.Parts) {2214            if (part.Thought) {2215                if (part.Text != null) {2216                    Console.WriteLine(part.Text);2217                } else if (part.InlineData != null) {2218                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);2219                    await File.WriteAllBytesAsync("image.png", imageBytes);2220                    Console.WriteLine("Image saved as image.png");2221                }2222            }2223        }2224    }22252226#### Controlling thinking levels22272228With Gemini 3.1 Flash Image and Gemini 3.1 Flash Lite Image, you can control the2229amount of thinking the model2230uses to balance quality and latency. The default `thinkingLevel` is `minimal`,2231and the supported levels are `minimal` and `high`. Setting the2232`thinkingLevel` to `minimal` provides the lowest latency responses. Note that2233minimal thinking does not mean the model uses no thinking at all.22342235You can add the `includeThoughts` boolean to determine whether the model's2236generated thoughts are returned in the response, or remain hidden.22372238### Python22392240    from google import genai22412242    response = client.models.generate_content(2243        model="gemini-3.1-flash-image",2244        contents="A futuristic city built inside a giant glass bottle floating in space",2245        config=types.GenerateContentConfig(2246            response_modalities=["IMAGE"],2247            thinking_config=types.ThinkingConfig(2248                thinking_level="High",2249                include_thoughts=True2250            ),2251        )2252    )22532254    for part in response.parts:2255        if part.thought: # Skip outputting thoughts2256          continue2257        if part.text:2258          display(Markdown(part.text))2259        elif image:= part.as_image():2260          image.show()22612262### JavaScript22632264    import { GoogleGenAI } from "@google/genai";2265    import * as fs from "node:fs";22662267    async function main() {22682269      const ai = new GoogleGenAI({});22702271      const response = await ai.models.generateContent({2272        model: "gemini-3.1-flash-image",2273        contents: "A futuristic city built inside a giant glass bottle floating in space",2274        config: {2275          responseModalities: ["IMAGE"],2276          thinkingConfig: {2277            thinkingLevel: "High",2278            includeThoughts: true2279          },2280        },2281      });22822283      for (const part of response.candidates[0].content.parts) {2284        if (part.thought) { // Skip outputting thoughts2285          continue;2286        }2287        if (part.text) {2288          console.log(part.text);2289        } else if (part.inlineData) {2290          const imageData = part.inlineData.data;2291          const buffer = Buffer.from(imageData, "base64");2292          fs.writeFileSync("image.png", buffer);2293          console.log("Image saved as image.png");2294        }2295      }2296    }2297    main();22982299### Go23002301    package main23022303    import (2304        "context"2305        "fmt"2306        "log"2307        "os"23082309        "google.golang.org/genai"2310        pb "google.golang.org/genai/schema"2311    )23122313    func main() {2314        ctx := context.Background()2315        client, err := genai.NewClient(ctx, nil)2316        if err != nil {2317            log.Fatal(err)2318        }2319        defer client.Close()23202321        model := client.GenerativeModel("gemini-3.1-flash-image")2322        model.GenerationConfig = &pb.GenerationConfig{2323            ResponseModalities: []pb.ResponseModality{genai.Image},2324            ThinkingConfig: &pb.ThinkingConfig{2325                ThinkingLevel:   "High",2326                IncludeThoughts: true,2327            },2328        }23292330        prompt := "A futuristic city built inside a giant glass bottle floating in space"2331        resp, err := model.GenerateContent(ctx, genai.Text(prompt))2332        if err != nil {2333            log.Fatal(err)2334        }23352336        for _, part := range resp.Candidates[0].Content.Parts {2337            if part.Thought { // Skip outputting thoughts2338                continue2339            }2340            if txt, ok := part.(genai.Text); ok {2341                fmt.Printf("%s", string(txt))2342            } else if img, ok := part.(genai.ImageData); ok {2343                err := os.WriteFile("image.png", img.Data, 0644)2344                if err != nil {2345                    log.Fatal(err)2346                }2347            }2348        }2349    }23502351### Java23522353    import com.google.genai.Client;2354    import com.google.genai.types.GenerateContentConfig;2355    import com.google.genai.types.GenerateContentResponse;2356    import com.google.genai.types.Part;2357    import com.google.genai.types.ThinkingConfig;23582359    import java.io.IOException;2360    import java.nio.file.Files;2361    import java.nio.file.Paths;23622363    public class ThinkingLevels {2364      public static void main(String[] args) throws IOException {23652366        try (Client client = new Client()) {2367          GenerateContentConfig config = GenerateContentConfig.builder()2368              .responseModalities("IMAGE")2369              .thinkingConfig(ThinkingConfig.builder()2370                  .thinkingLevel("High")2371                  .includeThoughts(true)2372                  .build())2373              .build();23742375          GenerateContentResponse response = client.models.generateContent(2376              "gemini-3.1-flash-image",2377              "A futuristic city built inside a giant glass bottle floating in space",2378              config);23792380          for (Part part : response.parts()) {2381            if (part.thought().orElse(false)) {2382              // Skip outputting thoughts2383              continue;2384            }2385            if (part.text().isPresent()) {2386              System.out.println(part.text().get());2387            } else if (part.inlineData().isPresent()) {2388              var blob = part.inlineData().get();2389              if (blob.data().isPresent()) {2390                Files.write(Paths.get("image.png"), blob.data().get());2391                System.out.println("Image saved as image.png");2392              }2393            }2394          }2395        }2396      }2397    }23982399### C#24002401    using Google.GenAI;2402    using System;2403    using System.Collections.Generic;2404    using System.IO;2405    using System.Threading.Tasks;24062407    public class ThinkingLevels {2408      public static async Task Main(string[] args) {2409        var client = new Client();24102411        var response = await client.Models.GenerateContentAsync(2412            model: "gemini-3.1-flash-image",2413            contents: new List<Part>2414            {2415                new Part { Text = "A futuristic city built inside a giant glass bottle floating in space" }2416            },2417            config: new GenerateContentConfig2418            {2419                ResponseModalities = new List<string> { "IMAGE" },2420                ThinkingConfig = new ThinkingConfig2421                {2422                    ThinkingLevel = "High",2423                    IncludeThoughts = true2424                }2425            }2426        );24272428        foreach (var candidate in response.Candidates) {2429            foreach (var part in candidate.Content.Parts) {2430                if (part.Thought) {2431                    // Skip outputting thoughts2432                    continue;2433                }2434                if (part.Text != null) {2435                    Console.WriteLine(part.Text);2436                } else if (part.InlineData != null) {2437                    var imageBytes = Convert.FromBase64String(part.InlineData.Data);2438                    await File.WriteAllBytesAsync("image.png", imageBytes);2439                    Console.WriteLine("Image saved as image.png");2440                }2441            }2442        }2443      }2444    }24452446### REST24472448    curl -s -X POST \2449      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \2450      -H "x-goog-api-key: $GEMINI_API_KEY" \2451      -H "Content-Type: application/json" \2452      -d '{2453        "contents": [{"parts": [{"text": "A futuristic city built inside a giant glass bottle floating in space"}]}],2454        "generationConfig": {2455          "responseModalities": ["IMAGE"],2456          "thinkingConfig": {2457            "thinkingLevel": "High",2458            "includeThoughts": true2459          }2460        }2461      }'24622463Note that thinking tokens are billed regardless of whether `includeThoughts` is2464set to `true` or `false`, as the [thinking process](https://ai.google.dev/gemini-api/docs/generate-content/image-generation#thinking-process) always2465happens by default whether you view the process or not.24662467#### Thought signatures24682469Thought signatures are encrypted representations of the2470model's internal thought process and are used to preserve reasoning context2471across multi-turn interactions. All responses include a `thought_signature`2472field. As a general rule, if you receive a thought signature in a model2473response, you should pass it back exactly as received when sending the2474conversation history in the next turn. Failure to circulate thought signatures2475may cause the response to fail. Check the [thought signature](https://ai.google.dev/gemini-api/docs/thought-signatures)2476documentation for more explanations of signatures overall.24772478> [!NOTE]2479> **Note:** If you use the official [Google Gen AI SDKs](https://ai.google.dev/gemini-api/docs/libraries) and use the chat feature (or append the full model response object directly to history), **thought signatures are handled automatically**. You do not need to manually extract or manage them, or change your code.24802481Here is how thought signatures work:24822483- All `inline_data` parts with image `mimetype` which are part of the response should have signature.2484- If there are some text parts at the beginning (before any image) right after the thoughts, the first text part should also have a signature.2485- If `inline_data` parts with image `mimetype` are part of thoughts, they won't have signatures.24862487The following code shows an example of where thought signatures are included:24882489    [2490      {2491        "inline_data": {2492          "data": "<base64_image_data_0>",2493          "mime_type": "image/png"2494        },2495        "thought": true // Thoughts don't have signatures2496      },2497      {2498        "inline_data": {2499          "data": "<base64_image_data_1>",2500          "mime_type": "image/png"2501        },2502        "thought": true // Thoughts don't have signatures2503      },2504      {2505        "inline_data": {2506          "data": "<base64_image_data_2>",2507          "mime_type": "image/png"2508        },2509        "thought": true // Thoughts don't have signatures2510      },2511      {2512        "text": "Here is a step-by-step guide to baking macarons, presented in three separate images.\n\n### Step 1: Piping the Batter\n\nThe first step after making your macaron batter is to pipe it onto a baking sheet. This requires a steady hand to create uniform circles.\n\n",2513        "thought_signature": "<Signature_A>" // The first non-thought part always has a signature2514      },2515      {2516        "inline_data": {2517          "data": "<base64_image_data_3>",2518          "mime_type": "image/png"2519        },2520        "thought_signature": "<Signature_B>" // All image parts have a signatures2521      },2522      {2523        "text": "\n\n### Step 2: Baking and Developing Feet\n\nOnce piped, the macarons are baked in the oven. A key sign of a successful bake is the development of \"feet\"---the ruffled edge at the base of each macaron shell.\n\n"2524        // Follow-up text parts don't have signatures2525      },2526      {2527        "inline_data": {2528          "data": "<base64_image_data_4>",2529          "mime_type": "image/png"2530        },2531        "thought_signature": "<Signature_C>" // All image parts have a signatures2532      },2533      {2534        "text": "\n\n### Step 3: Assembling the Macaron\n\nThe final step is to pair the cooled macaron shells by size and sandwich them together with your desired filling, creating the classic macaron dessert.\n\n"2535      },2536      {2537        "inline_data": {2538          "data": "<base64_image_data_5>",2539          "mime_type": "image/png"2540        },2541        "thought_signature": "<Signature_D>" // All image parts have a signatures2542      }2543    ]25442545## Other image generation modes25462547Gemini supports other image interaction modes based on prompt structure and2548context, including:25492550- **Text to image(s) and text (interleaved):** Outputs images with related text.2551  - Example prompt: "Generate an illustrated recipe for a paella."2552- **Image(s) and text to image(s) and text (interleaved)** : Uses input images and text to create new related images and text.2553  - Example prompt: (With an image of a furnished room) "What other color sofas would work in my space? can you update the image?"25542555## Generate images in batch25562557If you need to generate a lot of images, you can use the2558[Batch API](https://ai.google.dev/gemini-api/docs/batch-api). You get higher2559[rate limits](https://ai.google.dev/gemini-api/docs/rate-limits) in exchange for a turnaround of up2560to 24 hours.25612562Check the [Batch API image generation documentation](https://ai.google.dev/gemini-api/docs/batch-api#image-generation) and the [cookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Batch_mode.ipynb)2563for Batch API image examples and code.25642565## Prompting guide and strategies25662567Mastering image generation starts with one fundamental principle:2568> **Describe the scene, don't just list keywords.**2569> The model's core strength is its deep language understanding. A narrative,2570> descriptive paragraph will almost always produce a better, more coherent image2571> than a list of disconnected words.25722573### Prompts for generating images25742575The following strategies will help you create effective prompts to2576generate exactly the images you're looking for.25772578#### Photography25792580For realistic images, use photography terms. Mention camera angles, lens types,2581lighting, and fine details to guide the model toward a realistic result.25822583| **Prompt** | **Generated output** |2584|---|---|2585| A photo of a close-up portrait of an elderly Japanese ceramicist with deep, sun-etched wrinkles and a warm, knowing smile. He is carefully inspecting a freshly glazed tea bowl. The setting is his rustic, sun-drenched workshop. The scene is illuminated by soft, golden hour light streaming through a window, highlighting the fine texture of the clay. Captured with an 85mm portrait lens, resulting in a soft, blurred background (bokeh). The overall mood is serene and masterful. Vertical portrait orientation. | ![Elderly Japanese ceramicist](https://ai.google.dev/static/gemini-api/docs/images/photorealistic_example.png) |25862587#### Stylized illustrations and stickers25882589To create stickers, icons, or assets, be explicit about the style and request a2590white background.25912592> [!NOTE]2593> **Note:** The model does not support generating a transparent background.25942595| **Prompt** | **Generated output** |2596|---|---|2597| 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. | ![Kawaii red panda sticker](https://ai.google.dev/static/gemini-api/docs/images/red_panda_sticker.png) |25982599#### Accurate text in images26002601Gemini excels at rendering text. Be clear about the text, the font style2602(descriptively), and the overall design. Use Gemini 3 Pro Image for2603professional asset production.26042605| **Prompt** | **Generated output** |2606|---|---|2607| 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. | ![Coffee shop logo](https://ai.google.dev/static/gemini-api/docs/images/logo_example.jpg) |26082609#### Product mockups and commercial photography26102611Perfect for creating clean, professional product shots for ecommerce,2612advertising, or branding.26132614| **Prompt** | **Generated output** |2615|---|---|2616| 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. | ![Ceramic coffee mug product shot](https://ai.google.dev/static/gemini-api/docs/images/product_mockup.png) |26172618#### Minimalist and negative space design26192620Excellent for creating backgrounds for websites, presentations, or marketing2621materials where text will be overlaid.26222623| **Prompt** | **Generated output** |2624|---|---|2625| 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. | ![Minimalist design with red maple leaf](https://ai.google.dev/static/gemini-api/docs/images/minimalist_design.png) |26262627#### Sequential art (comic panel / storyboard)26282629Builds on character consistency and scene description to create panels for2630visual storytelling. For accuracy with text and storytelling ability, these2631prompts work best with Gemini 3.1 Pro and Gemini 3.1 Flash Image.26322633| **Prompt** | **Generated output** |2634|---|---|2635| **Input image:** ![Man in white glasses](https://ai.google.dev/static/gemini-api/docs/images/man_in_white_glasses.jpg) Input image **Prompt:** 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. | ![Gritty noir comic panel](https://ai.google.dev/static/gemini-api/docs/images/comic_panel.jpg) |26362637#### Grounding with Google Search26382639Use Google Search to generate images based on recent or real-time information.2640This is useful for news, weather, and other time-sensitive topics.26412642| **Prompt** | **Generated output** |2643|---|---|2644| Make a simple but stylish graphic of last night's Arsenal game in the Champion's League | ![Arsenal football score graphic](https://ai.google.dev/static/gemini-api/docs/images/football-score.jpg) |26452646### Prompts for editing images26472648These examples show how to provide images alongside your text prompts for2649editing, composition, and style transfer.26502651#### Adding and removing elements26522653Provide an image and describe your change. The model will match the original2654image's style, lighting, and perspective.26552656| **Prompt** | **Generated output** |2657|---|---|2658| **Input image:** :cat: Input image **Prompt:** 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 matches the soft lighting of the photo. | ![Cat with wizard hat](https://ai.google.dev/static/gemini-api/docs/images/cat_with_hat.png) |26592660#### Inpainting (semantic masking)26612662Conversationally define a "mask" to edit a specific part of an image while2663leaving the rest untouched.26642665| **Prompt** | **Generated output** |2666|---|---|2667| **Input image:** ![A wide shot of a modern, well-lit living room...](https://ai.google.dev/static/gemini-api/docs/images/living_room.png) Input image **Prompt:** 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. | ![Living room with brown leather sofa](https://ai.google.dev/static/gemini-api/docs/images/living_room_edited.png) |26682669#### Style transfer26702671Provide an image and ask the model to recreate its content in a different2672artistic style.26732674| **Prompt** | **Generated output** |2675|---|---|2676| **Input image:** ![A photorealistic, high-resolution photograph of a busy city street...](https://ai.google.dev/static/gemini-api/docs/images/city.png) Input image **Prompt:** 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. | ![City street in Starry Night style](https://ai.google.dev/static/gemini-api/docs/images/city_style_transfer.png) |26772678#### Advanced composition: combining multiple images26792680Provide multiple images as context to create a new, composite scene. This is2681perfect for product mockups or creative collages.26822683| **Prompt** | **Generated output** |2684|---|---|2685| **Input images:** :dress: Input 1: Dress ![Full-body shot of a woman with her hair in a bun...](https://ai.google.dev/static/gemini-api/docs/images/model.png) Input 2: Model **Prompt:** 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. | ![Fashion e-commerce shot](https://ai.google.dev/static/gemini-api/docs/images/fashion_ecommerce_shot.png) |26862687#### High-fidelity detail preservation26882689To ensure critical details (like a face or logo) are preserved during an edit,2690describe them in great detail along with your edit request.26912692| **Prompt** | **Generated output** |2693|---|---|2694| **Input images:** :woman: Input 1: Woman ![A simple, modern logo with the letters 'G' and 'A'...](https://ai.google.dev/static/gemini-api/docs/images/logo.png) Input 2: Logo **Prompt:** 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. | ![Woman with logo on t-shirt](https://ai.google.dev/static/gemini-api/docs/images/woman_with_logo.png) |26952696#### Bring something to life26972698Upload a rough sketch or drawing and ask the model to refine it into a finished image.26992700| **Prompt** | **Generated output** |2701|---|---|2702| **Input image:** ![Sketch of a car](https://ai.google.dev/static/gemini-api/docs/images/car-sketch.jpg) Rough sketch of a car **Prompt:** 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. | ![Polished photo of concept car](https://ai.google.dev/static/gemini-api/docs/images/car-photo.jpg) |27032704#### Character consistency: 360 view27052706You can generate 360-degree views of a character by iteratively prompting for2707different angles. For best results, include previously generated images in2708subsequent prompts to maintain consistency. For complex poses, include a2709reference image of the desired pose.27102711| **Prompt** | **Generated output** |2712|---|---|2713| **Input image:** ![Original input of a man in white glasses](https://ai.google.dev/static/gemini-api/docs/images/man_in_white_glasses.jpg) Original image **Prompt:** A studio portrait of this man against white, in profile looking right | ![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 |27142715### Best practices27162717To elevate your results from good to great, incorporate these professional2718strategies into your workflow.27192720- **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."2721- **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."2722- **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."2723- **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."2724- **Use "semantic negative prompts":** Instead of saying "no cars," describe the desired scene positively: "an empty, deserted street with no signs of traffic."2725- **Control the camera:** Use photographic and cinematic language to control the composition. Terms like `wide-angle shot`, `macro shot`, `low-angle2726  perspective`.27272728## Limitations27292730- 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.2731- 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.2732- The model won't always follow the exact number of image outputs that the user explicitly asks for.2733- `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.2734- When generating text for an image, Gemini works best if you first generate the text and then ask for an image with the text.2735- `gemini-3.1-flash-image` Grounding with Google Search does not support using real-world images of people from web search at this time.2736- All generated images include a [SynthID watermark](https://ai.google.dev/responsible/docs/safeguards/synthid).27372738## Optional configurations27392740You can optionally configure the response modalities and aspect ratio of the2741model's output in the `config` field of `generate_content` calls.27422743### Output types27442745The model defaults to returning text and image responses2746(i.e. `response_modalities=['Text', 'Image']`).2747You can configure the response to return only images without text using2748`response_modalities=['Image']`.27492750### Python27512752    response = client.models.generate_content(2753        model="gemini-3.1-flash-image",2754        contents=[prompt],2755        config=types.GenerateContentConfig(2756            response_modalities=['Image']2757        )2758    )27592760### JavaScript27612762    const response = await ai.models.generateContent({2763        model: "gemini-3.1-flash-image",2764        contents: prompt,2765        config: {2766            responseModalities: ['Image']2767        }2768      });27692770### Go27712772    result, _ := client.Models.GenerateContent(2773        ctx,2774        "gemini-3.1-flash-image",2775        genai.Text("Create a picture of a nano banana dish in a " +2776                    " fancy restaurant with a Gemini theme"),2777        &genai.GenerateContentConfig{2778            ResponseModalities: "Image",2779        },2780      )27812782### Java27832784    response = client.models.generateContent(2785        "gemini-3.1-flash-image",2786        prompt,2787        GenerateContentConfig.builder()2788            .responseModalities("IMAGE")2789            .build());27902791### C#27922793    var response = await client.Models.GenerateContentAsync(2794        model: "gemini-3.1-flash-image",2795        contents: new List<Part> { new Part { Text = prompt } },2796        config: new GenerateContentConfig2797        {2798            ResponseModalities = new List<string> { "IMAGE" }2799        }2800    );28012802### REST28032804    curl -s -X POST \2805      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \2806      -H "x-goog-api-key: $GEMINI_API_KEY" \2807      -H "Content-Type: application/json" \2808      -d '{2809        "contents": [{2810          "parts": [2811            {"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}2812          ]2813        }],2814        "generationConfig": {2815          "responseModalities": ["Image"]2816        }2817      }'28182819### Aspect ratios and image size28202821The model defaults to matching the output image size to that of your input2822image, or otherwise generates 1:1 squares.2823You can control the aspect ratio of the output image using the `aspect_ratio`2824field under `response_format` in the response request, shown here:28252826### Python28272828    # For gemini-2.5-flash-image2829    response = client.models.generate_content(2830        model="gemini-2.5-flash-image",2831        contents=[prompt],2832        config=types.GenerateContentConfig(2833            response_format={"image": {aspect_ratio: "16:9",}}2834        )2835    )28362837    # For gemini-3.1-flash-image and gemini-3-pro-image2838    response = client.models.generate_content(2839        model="gemini-3.1-flash-image",2840        contents=[prompt],2841        config=types.GenerateContentConfig(2842            response_format={"image": {aspect_ratio: "16:9",                 image_size: "2K",}}2843        )2844    )28452846### JavaScript28472848    // For gemini-2.5-flash-image2849    const response = await ai.models.generateContent({2850        model: "gemini-2.5-flash-image",2851        contents: prompt,2852        config: {2853          responseFormat: {2854        image: {2855            aspectRatio: "16:9",2856          }2857      },2858        }2859      });28602861    // For gemini-3.1-flash-image and gemini-3-pro-image2862    const response_gemini3 = await ai.models.generateContent({2863        model: "gemini-3.1-flash-image",2864        contents: prompt,2865        config: {2866          responseFormat: {2867        image: {2868            aspectRatio: "16:9",2869            imageSize: "2K",2870          }2871      },2872        }2873      });28742875### Go28762877    // For gemini-2.5-flash-image2878    result, _ := client.Models.GenerateContent(2879        ctx,2880        "gemini-2.5-flash-image",2881        genai.Text("Create a picture of a nano banana dish in a " +2882                    " fancy restaurant with a Gemini theme"),2883        &genai.GenerateContentConfig{2884            ImageConfig: &genai.ImageConfig{2885              AspectRatio: "16:9",2886            },2887        }2888      )28892890    // For gemini-3.1-flash-image and gemini-3-pro-image2891    result_gemini3, _ := client.Models.GenerateContent(2892        ctx,2893        "gemini-3.1-flash-image",2894        genai.Text("Create a picture of a nano banana dish in a " +2895                    " fancy restaurant with a Gemini theme"),2896        &genai.GenerateContentConfig{2897            ImageConfig: &genai.ImageConfig{2898              AspectRatio: "16:9",2899              ImageSize: "2K",2900            },2901        }2902      )29032904### Java29052906    // For gemini-2.5-flash-image2907    response = client.models.generateContent(2908        "gemini-2.5-flash-image",2909        prompt,2910        GenerateContentConfig.builder()2911            .imageConfig(ImageConfig.builder()2912                .aspectRatio("16:9")2913                .build())2914            .build());29152916    // For gemini-3.1-flash-image and gemini-3-pro-image2917    response_gemini3 = client.models.generateContent(2918        "gemini-3.1-flash-image",2919        prompt,2920        GenerateContentConfig.builder()2921            .imageConfig(ImageConfig.builder()2922                .aspectRatio("16:9")2923                .imageSize("2K")2924                .build())2925            .build());29262927### C#29282929    // For gemini-2.5-flash-image2930    var response = await client.Models.GenerateContentAsync(2931        model: "gemini-2.5-flash-image",2932        contents: new List<Part> { new Part { Text = prompt } },2933        config: new GenerateContentConfig2934        {2935            ImageConfig = new ImageConfig2936            {2937                AspectRatio = "16:9"2938            }2939        }2940    );29412942    // For gemini-3.1-flash-image and gemini-3-pro-image2943    var response_gemini3 = await client.Models.GenerateContentAsync(2944        model: "gemini-3.1-flash-image",2945        contents: new List<Part> { new Part { Text = prompt } },2946        config: new GenerateContentConfig2947        {2948            ImageConfig = new ImageConfig2949            {2950                AspectRatio = "16:9",2951                ImageSize = "2K"2952            }2953        }2954    );29552956### REST29572958    # For gemini-2.5-flash-image2959    curl -s -X POST \2960      "https://generativelanguage.googleapis.com/v1/models/gemini-2.5-flash-image:generateContent" \2961      -H "x-goog-api-key: $GEMINI_API_KEY" \2962      -H 'Content-Type: application/json' \2963      -d '{2964        "contents": [{2965          "parts": [2966            {"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}2967          ]2968        }],2969        "generationConfig": {2970          "responseFormat": {2971        "image": {2972            "aspectRatio": "16:9"2973          }2974      }2975        }2976      }'29772978    # For gemini-3-pro-image2979    curl -s -X POST \2980      "https://generativelanguage.googleapis.com/v1/models/gemini-3.1-flash-image:generateContent" \2981      -H "x-goog-api-key: $GEMINI_API_KEY" \2982      -H 'Content-Type: application/json' \2983      -d '{2984        "contents": [{2985          "parts": [2986            {"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}2987          ]2988        }],2989        "generationConfig": {2990          "responseFormat": {2991        "image": {2992            "aspectRatio": "16:9",2993            "imageSize": "2K"2994          }2995      }2996        }2997      }'29982999The different ratios available and the size of the image generated are listed in3000the following tables:30013002### 3.1 Flash Image30033004| Aspect ratio | 512 resolution | 0.5K tokens | 1K resolution | 1K tokens | 2K resolution | 2K tokens | 4K resolution | 4K tokens |3005|---|---|---|---|---|---|---|---|---|3006| **1:1** | 512x512 | 747 | 1024x1024 | 1120 | 2048x2048 | 1680 | 4096x4096 | 2520 |3007| **1:4** | 256x1024 | 747 | 512x2048 | 1120 | 1024x4096 | 1680 | 2048x8192 | 2520 |3008| **1:8** | 192x1536 | 747 | 384x3072 | 1120 | 768x6144 | 1680 | 1536x12288 | 2520 |3009| **2:3** | 424x632 | 747 | 848x1264 | 1120 | 1696x2528 | 1680 | 3392x5056 | 2520 |3010| **3:2** | 632x424 | 747 | 1264x848 | 1120 | 2528x1696 | 1680 | 5056x3392 | 2520 |3011| **3:4** | 448x600 | 747 | 896x1200 | 1120 | 1792x2400 | 1680 | 3584x4800 | 2520 |3012| **4:1** | 1024x256 | 747 | 2048x512 | 1120 | 4096x1024 | 1680 | 8192x2048 | 2520 |3013| **4:3** | 600x448 | 747 | 1200x896 | 1120 | 2400x1792 | 1680 | 4800x3584 | 2520 |3014| **4:5** | 464x576 | 747 | 928x1152 | 1120 | 1856x2304 | 1680 | 3712x4608 | 2520 |3015| **5:4** | 576x464 | 747 | 1152x928 | 1120 | 2304x1856 | 1680 | 4608x3712 | 2520 |3016| **8:1** | 1536x192 | 747 | 3072x384 | 1120 | 6144x768 | 1680 | 12288x1536 | 2520 |3017| **9:16** | 384x688 | 747 | 768x1376 | 1120 | 1536x2752 | 1680 | 3072x5504 | 2520 |3018| **16:9** | 688x384 | 747 | 1376x768 | 1120 | 2752x1536 | 1680 | 5504x3072 | 2520 |3019| **21:9** | 792x168 | 747 | 1584x672 | 1120 | 3168x1344 | 1680 | 6336x2688 | 2520 |30203021### 3.1 Flash Lite Image30223023| Aspect ratio | 512 resolution | 0.5K tokens | 1K resolution | 1K tokens |3024|---|---|---|---|---|3025| **1:1** | 512x512 | 747 | 1024x1024 | 1120 |3026| **1:4** | 256x1024 | 747 | 512x2048 | 1120 |3027| **1:8** | 192x1536 | 747 | 384x3072 | 1120 |3028| **2:3** | 424x632 | 747 | 848x1264 | 1120 |3029| **3:2** | 632x424 | 747 | 1264x848 | 1120 |3030| **3:4** | 448x600 | 747 | 896x1200 | 1120 |3031| **4:1** | 1024x256 | 747 | 2048x512 | 1120 |3032| **4:3** | 600x448 | 747 | 1200x896 | 1120 |3033| **4:5** | 464x576 | 747 | 928x1152 | 1120 |3034| **5:4** | 576x464 | 747 | 1152x928 | 1120 |3035| **8:1** | 1536x192 | 747 | 3072x384 | 1120 |3036| **9:16** | 384x688 | 747 | 768x1376 | 1120 |3037| **16:9** | 688x384 | 747 | 1376x768 | 1120 |3038| **21:9** | 792x168 | 747 | 1584x672 | 1120 |30393040### 3.1 Pro Image30413042| Aspect ratio | 1K resolution | 1K tokens | 2K resolution | 2K tokens | 4K resolution | 4K tokens |3043|---|---|---|---|---|---|---|3044| **1:1** | 1024x1024 | 1120 | 2048x2048 | 1120 | 4096x4096 | 2000 |3045| **2:3** | 848x1264 | 1120 | 1696x2528 | 1120 | 3392x5056 | 2000 |3046| **3:2** | 1264x848 | 1120 | 2528x1696 | 1120 | 5056x3392 | 2000 |3047| **3:4** | 896x1200 | 1120 | 1792x2400 | 1120 | 3584x4800 | 2000 |3048| **4:3** | 1200x896 | 1120 | 2400x1792 | 1120 | 4800x3584 | 2000 |3049| **4:5** | 928x1152 | 1120 | 1856x2304 | 1120 | 3712x4608 | 2000 |3050| **5:4** | 1152x928 | 1120 | 2304x1856 | 1120 | 4608x3712 | 2000 |3051| **9:16** | 768x1376 | 1120 | 1536x2752 | 1120 | 3072x5504 | 2000 |3052| **16:9** | 1376x768 | 1120 | 2752x1536 | 1120 | 5504x3072 | 2000 |3053| **21:9** | 1584x672 | 1120 | 3168x1344 | 1120 | 6336x2688 | 2000 |30543055### Gemini 2.5 Flash Image30563057| Aspect ratio | Resolution | Tokens |3058|---|---|---|3059| 1:1 | 1024x1024 | 1290 |3060| 2:3 | 832x1248 | 1290 |3061| 3:2 | 1248x832 | 1290 |3062| 3:4 | 864x1184 | 1290 |3063| 4:3 | 1184x864 | 1290 |3064| 4:5 | 896x1152 | 1290 |3065| 5:4 | 1152x896 | 1290 |3066| 9:16 | 768x1344 | 1290 |3067| 16:9 | 1344x768 | 1290 |3068| 21:9 | 1536x672 | 1290 |30693070## Model selection30713072Choose the model best suited for your specific use case.30733074- **Gemini 3.1 Flash Image (Nano Banana 2)** should be your3075  go-to image generation model, as the best all around performance and3076  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 more3077  details.30783079- **Gemini 3.1 Flash Lite Image (Nano Banana 2 Lite)** is designed as3080  the efficiency specialist of the image generation family, offering3081  ultra-low latency and cost-effective image generation and editing.3082  Check the model [pricing](https://ai.google.dev/gemini-api/docs/pricing#gemini-3.1-flash-lite-image)3083  and [capabilities](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite-image) page3084  for more details.30853086- **Gemini 3 Pro Image (Nano Banana Pro)** is designed for3087  professional asset production and complex instructions. This model features3088  real-world grounding using Google Search, a default "Thinking" process that3089  refines composition prior to generation, and can generate images of up to 4K3090  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 more3091  details.30923093- **Gemini 2.5 Flash Image (Nano Banana)** is designed for speed and3094  efficiency. This model is optimized for high-volume, low-latency tasks and3095  generates images at 1024px resolution. Check the model [pricing](https://ai.google.dev/gemini-api/docs/pricing#gemini-2.5-flash-image) and3096  [capabilities](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-image) page for more3097  details.30983099### When to use Imagen31003101> [!WARNING]3102> Imagen models are deprecated and will be shut down on August 17, 2026. We recommend using Nano Banana models for all image generation tasks.31033104In addition to using Gemini's built-in image generation capabilities, you can3105also access [Imagen](https://ai.google.dev/gemini-api/docs/imagen), our specialized image generation3106model, through the Gemini API. Plan to migrate before the shutdown date.31073108## What's next31093110- Find more examples and code samples in the [cookbook guide](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Get_Started_Nano_Banana.ipynb).3111- Check out the [Veo guide](https://ai.google.dev/gemini-api/docs/video) to learn how to generate videos with the Gemini API.3112- To learn more about Gemini models, see [Gemini models](https://ai.google.dev/gemini-api/docs/models/gemini).
Files main
Menu

Theme