تولید تصویر با Nano Banana

با پیام‌واره، برنامه‌های کاملاً کاربردی و دارای رابط کاربری کامل نمونه‌سازی کنید و ‫Nano Banana 2 را که با ابزارها، داده‌ها، و بوم‌سازگان Gemini ادغام شده است ببینید. همه این‌ها قبل‌از نوشتن حتی یک خط کد.
  • یا از پیام‌واره‌ها خودتان بسازید:
  • مجله لندن بازگرداندن موز کافه حرف تعریف سگ ایزومتریک
  • مجله
    تولیدشده توسط Nano Banana 2
    پیام‌واره: «عکسی از جلد مجله‌ای براق، جلد آبی ساده‌ای که کلمات بزرگ و پررنگ Nano Banana روی آن نوشته شده است. نوشتار با قلم سریف نوشته شده است و نما را پر می‌کند. نوشتار دیگری ندارد. در جلوی نوشتار، پرتره‌ای از فردی با لباسی شیک و ساده قرار دارد. او به‌صورت بازیگوشانه عدد ۲ را که نقطه کانونی است نگه داشته است.
    شماره نسخه و تاریخ «فوریه ۲۰۲۶» را به‌همراه بارکد در گوشه قرار دهید. مجله روی قفسه‌ای در کنار دیواری گچی به رنگ نارنجی در فروشگاه طراحان قرار دارد.»
  • لندن
    تولیدشده با Nano Banana Pro
    پیام‌واره: «صحنه کارتونی سه‌بعدی مینیاتوری ایزومتریک از بالا با زاویه ۴۵ درجه از لندن ارائه بده که واضح باشد و نمادین‌ترین نشان‌های معماری آن را نشان دهد. از بافت‌های نرم و پالایش‌شده با مواد PBR واقع‌گرایانه و نورپردازی و سایه‌های ملایم و طبیعی استفاده کنید. وضعیت آب‌وهوای کنونی را مستقیماً در محیط شهر ادغام کن تا فضایی فراگیر و اتمسفری ایجاد شود. از ترکیب‌بندی تمیز و مینیمالیستی با پس‌زمینه نرم و یک‌رنگ استفاده کن. در مرکز بالا، عنوان «لندن» را با نوشتار پررنگ بزرگ، نماد آب‌وهوای برجسته در زیر آن، سپس تاریخ (نوشتار کوچک) و دما (نوشتار متوسط) را قرار بده. همه نوشتارها باید با فاصله‌گذاری یکسان در مرکز قرار بگیرند و ممکن است به‌طور نامحسوس با بالای ساختمان‌ها هم‌پوشانی داشته باشند.»
  • کتزال
    تولیدشده توسط Nano Banana 2
    پیام‌واره: «از جستجوی تصویر برای پیدا کردن تصاویر دقیق از پرنده باشکوه کِتزال استفاده کن. کاغذدیواری زیبایی با نسبت ۳:۲ از این پرنده با گرادیان طبیعی از بالا به پایین و ترکیب‌بندی مینیمال بساز."
  • موز
    تولیدشده با Nano Banana Pro
    پیام‌واره: «این نشان‌واره را روی آگهی سطح بالایی برای عطر با رایحه موز قرار بده. نشان‌واره به‌طور کامل در بطری ادغام شده است.»
  • کافه
    تولیدشده با Nano Banana Pro
    پیام‌واره: «عکسی از صحنه‌ای روزمره در کافه‌ای شلوغ که صبحانه سرو می‌کند. در پیش‌زمینه مردی انیمه‌ای با موهای آبی، یکی از افراد طراحی با مداد، و دیگری شخصیتی با پویانمایی خمیری است"
  • حرف تعریف
    تولیدشده با Nano Banana Pro
    پیام‌واره: «از جستجو استفاده کن تا ببینی عرضه Gemini 3 Flash چگونه مورد استقبال قرار گرفته است. از این اطلاعات برای نوشتن مقاله‌ای کوتاه درباره آن (با سرتیتر) استفاده کنید. عکسی از مقاله را همان‌طور که در مجله براق با تمرکز بر طراحی ظاهر شده است برگردان. این عکس یک صفحه تاشده است که مقاله مربوط به Gemini 3 Flash را نشان می‌دهد. یک عکس اصلی. عنوان با قلم سریف.»
  • سگ
    تولیدشده با Nano Banana Pro
    پیام‌واره: «نمادی که سگی بانمک را نشان می‌دهد. پس‌زمینه سفید است. نمادها را به‌سبک سه‌بعدی رنگارنگ و لمسی بساز. نوشتاری وجود ندارد.»
  • ایزومتریک
    تولیدشده توسط Nano Banana 2
    پیام‌واره: «عکسی بساز که کاملاً ایزومتریک باشد. این یک مینیاتور نیست، بلکه عکسی است که اتفاقاً کاملاً ایزومتریک گرفته شده است. این عکس باغی مدرن و زیبا است. استخر بزرگی به‌شکل عدد ۲ و کلمات «Nano Banana 2» وجود دارد.

Nano Banana نام قابلیت‌های تولید تصویر بومی Gemini است. ‫Gemini می‌تواند تصاویر را به‌صورت مکالمه‌ای با نوشتار، تصویر، ویدیو، یا ترکیبی از آن‌ها تولید و پردازش کند. این ویژگی به شما امکان می‌دهد با کنترل بی‌سابقه، عناصر دیداری را ایجاد، ویرایش، و تکرار کنید.

انتخاب مدل

‫Nano Banana به مدل‌های زیر که در «میانای برنامه‌سازی کاربردی Gemini» دردسترس است اشاره دارد:

  • ‫Nano Banana 2.1 (Gemini Nano Banana 2.1) (gemini-nano-banana-2.1): به‌روزرسانی Nano Banana 2 که به‌عنوان مدل اصلی با کارایی بالا برای تولید تصویر و ویرایش مکالمه‌ای عمل می‌کند. این مدل درحالی‌که کیفیت دیداری، پرداز زدن نوشتار، سازگاری چندنوبتی، و زمینه‌سازی «جستجوی Google» را در وضوح تصویر ۱، ۲، و ۴ هزار بهبود می‌بخشد، سرعت و کارآمدی هزینه در سطح Flash را حفظ می‌کند.
  • ‫Nano Banana 2 Lite (تصویر Gemini 3.1 Flash Lite) (gemini-3.1-flash-lite-image): سریع‌ترین و ارزان‌ترین مدل تصویر Gemini که برای سرعت و مقیاس طراحی شده است و در آن سرعت و هزینه محدودیت‌های عملیاتی اصلی هستند. برای چندین ورودی مرجع یا ویرایش ترتیبی چندنوبتی بهینه نشده است.
  • ‫Nano Banana 2 (تصویر Gemini 3.1 Flash) (gemini-3.1-flash-image): مدل کارآمد نسل قبلی که سرعت را با تولید 4K، دانش جهانی، و پایداری تصویر چندمرجعی متعادل می‌کند. توصیه می‌شود برای همه پروژه‌های جدید از Nano Banana 2.1 استفاده کنید.
  • ‫Nano Banana Pro (تصویر Gemini 3 Pro) (gemini-3-pro-image): انتخاب ممتاز برای پیچیده‌ترین وظایف تصویری، ارائه بالاترین سطح دانش جهانی، بومی‌سازی پیشرفته، ثبات دقیق نمانام، و کنترل خلاقانه دقیق.
  • ‫Nano Banana (تصویر Gemini 2.5 Flash) (gemini-2.5-flash-image): پیشگام قدیمی سری Nano Banana. اگرچه این مدل همواره قابل‌اعتماد بوده است، مسیر انتقال توصیه‌شده این است که به Nano Banana 2 Lite منتقل شوید تا کیفیت بهبودیافته، سرعت تولید سریع‌تر، و قیمت پایین‌تر «میانای برنامه‌سازی کاربردی» را تجربه کنید.

همه تصاویر تولیدشده حاوی ته‌نقش SynthID هستند.

تولید تصویر (نوشتار به تصویر)

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",
)

with open("generated_image.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {

  const ai = new GoogleGenAI({});

  const prompt =
    "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: prompt,
  });
  const generatedImage = interaction.output_image;
  if (generatedImage) {
    const buffer = Buffer.from(generatedImage.data, "base64");
    fs.writeFileSync("gemini-native-image.png", buffer);
    console.log("Image saved as gemini-native-image.png");
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("generated_image.png"), imageBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("generated_image.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
    ]
  }'

می‌توانید داده‌های تصویر تولیدشده را بااستفاده از interaction.output_image دارایی بازیابی کنید که آخرین بلوک تصویر تولیدشده را برمی‌گرداند. برای جزئیات مربوط به ویژگی‌های راحتی، نمای کلی تعاملات را ببینید.

ویرایش تصویر (نوشتار و تصویر به تصویر)

یادآوری: مطمئن شوید که حقوق لازم را برای هر تصویری که بارگذاری می‌کنید داشته باشید. محتوایی را که ناقض حقوق دیگران است تولید نکنید، ازجمله ویدیوها یا تصاویری که دیگران را فریب یا آزار می‌دهند یا به آن‌ها آسیب می‌رسانند. استفاده شما از این سرویس هوش مصنوعی زایا تابع خط‌مشی کاربردهای غیرمجاز ما است.

تصویری ارائه دهید و از پیام‌واره‌های نوشتاری برای افزودن، برداشتن، یا اصلاح عناصر، تغییر سبک، یا اصلاح درجه رنگ استفاده کنید.

مثال زیر بارگذاری base64 تصویر کدبندی‌شده را نشان می‌دهد. برای تصاویر متعدد، داده‌برهای بزرگ‌تر، و انواع MIME پشتیبانی‌شده، صفحه درک تصویر را بررسی کنید.

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open("/path/to/cat_image.png", "rb") as f:
    image_bytes = f.read()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
          "type": "text",
          "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        }
    ],
)

with open("generated_image.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {

  const ai = new GoogleGenAI({});

  const imagePath = "path/to/cat_image.png";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  const prompt = [
    { type: "text", text: "Create a picture of my cat eating a nano-banana in a" +
            "fancy restaurant under the Gemini constellation" },
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image
    },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: prompt,
  });
  const generatedImage = interaction.output_image;
  if (generatedImage) {
    const buffer = Buffer.from(generatedImage.data, "base64");
    fs.writeFileSync("gemini-native-image.png", buffer);
    console.log("Image saved as gemini-native-image.png");
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] inputBytes = Files.readAllBytes(Paths.get("/path/to/cat_image.png"));
String base64Image = Base64.getEncoder().encodeToString(inputBytes);

Content textContent =
    TextContent.builder()
        .text("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme")
        .build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();

List contents = Arrays.asList(textContent, imageContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] outputBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("generated_image.png"), outputBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    inputBytes, err := os.ReadFile("/path/to/cat_image.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(inputBytes)

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput([]interactions.Content{
                interactions.NewContent(interactions.TextContent{
                    Text: "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",
                }),
                interactions.NewContent(interactions.ImageContent{
                    Data:     genai.Ptr(base64Image),
                    MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
                }),
            }),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        outputBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("generated_image.png", outputBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"text\", \"text\": \"Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"},
        {
          \"type\": \"image\",
          \"mime_type\": \"image/jpeg\",
          \"data\": \"\"
        }
      ]
    }"

ویرایش چندنوبتی تصویر

به تولید و ویرایش کردن تصویرها به‌صورت مکالمه‌ای ادامه دهید. مکالمه چند نوبتی روش توصیه‌شده برای تکرار کردن تصاویر است. مثال زیر پیام‌واره‌ای را برای تولید اطلاع‌نگاشت درباره فتوسنتز نشان می‌دهد.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.",
    tools=[{"type": "google_search"}],
)

with open("photosynthesis.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({});

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.",
    tools: [{"type": "google_search"}],
  });

  const generatedImage = interaction.output_image;
  if (generatedImage) {
    const buffer = Buffer.from(generatedImage.data, "base64");
    fs.writeFileSync("photosynthesis.png", buffer);
    console.log("Image saved as photosynthesis.png");
  }
}

await main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "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."))
        .tools(Arrays.asList(new GoogleSearch()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("photosynthesis.png"), imageBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(`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.`),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("photosynthesis.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plants favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids cookbook, suitable for a 4th grader."}
    ],
    "tools": [{"type": "google_search"}]
  }'
اطلاع‌نگاشت تولیدشده با هوش مصنوعی درباره فتوسنتز
اینفوگرافیک تولیدشده با هوش مصنوعی درباره فتوسنتز

سپس می‌توانید از previous_interaction_id برای تغییر زبان گرافیک به اسپانیایی استفاده کنید.

Python

interaction_2 = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Update this infographic to be in Spanish. Do not change any other elements of the image.",
    previous_interaction_id=interaction.id,
    response_format={
        "type": "image",
        "mime_type": "image/jpeg",
        "aspect_ratio": "16:9",
        "image_size": "2K"
    },
)

generated_image = interaction_2.output_image
if generated_image:
    with open("photosynthesis_spanish.png", "wb") as f:
        f.write(base64.b64decode(generated_image.data))

JavaScript

const interaction2 = await ai.interactions.create({
  model: "gemini-nano-banana-2.1",
  input: "Update this infographic to be in Spanish. Do not change any other elements of the image.",
  previous_interaction_id: interaction.id,
  response_format: {
    type: "image",
    mime_type: "image/png",
    aspect_ratio: "16:9",
    image_size: "2K"
  },
});

const generatedImage = interaction2.output_image;
if (generatedImage) {
  const buffer = Buffer.from(generatedImage.data, "base64");
  fs.writeFileSync("photosynthesis_spanish.png", buffer);
}

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction turn1Params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food."))
        .tools(Arrays.asList(new GoogleSearch()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(turn1Params)).interaction().get();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .imageSize(ImageResponseFormatImageSize.TWO_K)
                .build()));

CreateModelInteraction turn2Params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Update this infographic to be in Spanish. Do not change any other elements of the image."))
        .previousInteractionId(interaction.id().orElse(""))
        .responseFormat(format)
        .build();

Interaction interaction2 =
    client.interactions.create(CreateInteractionRequestBody.of(turn2Params)).interaction().get();

if (interaction2.outputImage().isPresent()
    && interaction2.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction2.outputImage().get().data().get());
  Files.write(Paths.get("photosynthesis_spanish.png"), imageBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food."),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeTwoK.ToPointer(),
        }),
    )

    res2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:                 interactions.Model("gemini-nano-banana-2.1"),
            Input:                 interactions.NewInteractionsInput("Update this infographic to be in Spanish. Do not change any other elements of the image."),
            PreviousInteractionID: res1.Interaction.ID,
            ResponseFormat:        genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res2.Interaction.OutputImage != nil && res2.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res2.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("photosynthesis_spanish.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Update this infographic to be in Spanish. Do not change any other elements of the image.",
    "previous_interaction_id": "",
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "aspect_ratio": "16:9",
      "image_size": "2K"
    }
  }'
اطلاع‌نگاشت هوش مصنوعی از فتوسنتز به زبان اسپانیایی
اینفوگرافیک تولیدشده با هوش مصنوعی از فتوسنتز به زبان اسپانیایی

ویژگی‌های Nano Banana

مدل‌های Nano Banana پیشرفته‌ترین تولید و ویرایش تصویر را ارائه می‌دهند. ‫Gemini Nano Banana 2.1 و Gemini 3.1 Flash Image برای سرعت و موارد استفاده با حجم بالا بهینه‌سازی شده‌اند، و Gemini 3 Pro Image برای تولید دارایی حرفه‌ای بهینه‌سازی شده است. این مدل‌ها که برای مقابله با چالش‌برانگیزترین گردش‌های کار ازطریق استدلال پیشرفته طراحی شده‌اند، در تکالیف پیچیده و چندمرحله‌ای ایجاد و اصلاح برتری دارند.

  • برونداد با وضوح بالا: قابلیت‌های تولید داخلی برای تصاویر 1K،‏ 2K، و 4K.
    • تصویر Gemini 3.1 Flash وضوح کوچک‌تر ۵۱۲ پیکسل (۰٫۵ هزار) را اضافه می‌کند (در Gemini Nano Banana 2.1 پشتیبانی نمی‌شود).
    • تصویر Gemini 3.1 Flash Lite فقط از وضوح 1K پشتیبانی می‌کند.
  • پرداز کردن نوشتار پیشرفته: توانایی تولید نوشتار سبک‌دار و خوانا برای اطلاع‌نگاشت‌ها، منوها، نمودارها، و دارایی‌های بازاریابی.
  • پایه‌گذاری با «جستجوی Google»: مدل می‌تواند از «جستجوی Google» به‌عنوان ابزاری برای تأیید حقایق و تولید تصاویر براساس داده‌های هم‌زمان (برای نمونه، نقشه‌های آب‌وهوای کنونی، نمودارهای سهام، رویدادهای اخیر) استفاده کند.
    • مدل تصویر Gemini 3.1 Flash Lite از آن پشتیبانی نمی‌کند.
    • ‫Gemini Nano Banana 2.1 و Gemini 3.1 Flash Image ادغام «پایه جستجوی تصویر Google» را در کنار «جستجوی وب» اضافه می‌کنند.
  • حالت «اندیشگر»: مدل از فرایند «اندیشیدن» برای استدلال کردن درباره پیام‌واره‌های پیچیده استفاده می‌کند. این ویژگی «تصاویر فکری» موقتی (در زیرینه قابل‌مشاهده است اما هزینه‌ای ندارد) تولید می‌کند تا ترکیب‌بندی را قبل‌از تولید برونداد نهایی با کیفیت بالا اصلاح کند.
  • حداکثر ۱۴ تصویر مرجع: حداکثر ۱۴ تصویر مرجع را ترکیب کنید تا تصویر نهایی تولید شود.
  • نسبت‌های ابعادی جدید: Gemini 3.1 Flash Lite Image نسبت‌های ابعادی 1:1، 3:2، 2:3، 3:4، 4:3، 4:5، 5:4، 9:16، 16:9، 21:9 را اضافه می‌کند.

استفاده از حداکثر ۱۴ تصویر مرجع

مدل‌های Nano Banana به شما امکان می‌دهند تا حداکثر ۱۴ تصویر مرجع را ترکیب کنید. این ۱۴ تصویر می‌تواند شامل موارد زیر باشد:

تصویر Gemini 3.1 Flash Lite ‫Gemini Nano Banana 2.1 و Gemini 3.1 Flash Image تصویر Gemini 3 Pro
حداکثر ۱۴ تصویر از اشیای با وفاداری بالا برای گنجاندن در تصویر نهایی حداکثر ۱۰ تصویر از اشیای با وفاداری بالا برای گنجاندن در تصویر نهایی حداکثر ۶ تصویر از اشیای با وفاداری بالا برای گنجاندن در تصویر نهایی
موجود نیست حداکثر ۴ تصویر از شخصیت‌ها برای حفظ یکپارچگی شخصیت حداکثر ۵ تصویر از شخصیت‌ها برای حفظ یکپارچگی شخصیت
موجود نیست موجود نیست حداکثر ۳ تصویر برای استفاده به‌عنوان مرجع سبک

Python

from google import genai
from google.genai import types
from PIL import Image
import base64

prompt = "An office group photo of these people, they are making funny faces."

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "text",
            "text": prompt,
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
    ],
    response_format={
        "type": "image",
        "aspect_ratio": "5:4",
        "image_size": "2K"
    },
)

with open("office.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const input = [
    {
      type: "text",
      text: "An office group photo of these people, they are making funny faces.",
    },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile1 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile2 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile3 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile4 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile5 },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
    response_format: {
      type: "image",
      aspect_ratio: "5:4",
      image_size: "2K",
    },
  });

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('office.png', buffer);
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

String prompt = "An office group photo of these people, they are making funny faces.";

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/person.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);

Content textContent = TextContent.builder().text(prompt).build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();

List contents =
    Arrays.asList(
        textContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent);

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("5:4"))
                .imageSize(ImageResponseFormatImageSize.TWO_K)
                .build()));

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] outBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("office.png"), outBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    prompt := "An office group photo of these people, they are making funny faces."

    imageBytes, err := os.ReadFile("/path/to/person.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)

    textContent := interactions.NewContent(interactions.TextContent{
        Text: prompt,
    })
    imageContent := interactions.NewContent(interactions.ImageContent{
        Data:     genai.Ptr(base64Image),
        MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
    })

    contents := []interactions.Content{
        textContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent,
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("5:4").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeTwoK.ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(contents),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        outBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("office.png", outBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"text\", \"text\": \"An office group photo of these people, they are making funny faces.\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"\"}
      ],
      \"response_format\": {
        \"type\": \"image\",
        \"aspect_ratio\": \"5:4\",
        \"image_size\": \"2K\"
      }
    }"
عکس گروهی اداری تولیدشده با هوش مصنوعی
عکس گروهی دفتر کار تولیدشده با هوش مصنوعی

پایه‌مندسازی با «جستجوی Google»

از ابزار «جستجوی Google» برای تولید تصاویر براساس اطلاعات بلادرنگ، مانند پیش‌بینی‌های آب‌وهوا، نمودارهای سهام، یا رویدادهای اخیر استفاده کنید.

توجه داشته باشید که هنگام استفاده از «زمینه» با «جستجوی Google» با تولید تصویر، نتایج جستجوی مبتنی بر تصویر به مدل تولید منتقل نمی‌شود و از پاسخ کنار گذاشته می‌شود (به زمینه با «جستجوی تصویر Google» مراجعه کنید)

Python

from google import genai
from google.genai import types
import base64
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"

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=prompt,
    tools=[{"type": "google_search"}],
    response_format={
        "type": "image",
        "mime_type": "image/jpeg",
        "aspect_ratio": "16:9"
    },
)

with open("weather.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day",
    tools: [{"type": "google_search"}],
    response_format: {
      type: "image",
      mime_type: "image/png",
      aspect_ratio: "16:9",
      image_size: "2K"
    },
  });

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('weather.png', buffer);
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

String 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";

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.of(prompt))
        .tools(Arrays.asList(new GoogleSearch()))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("weather.png"), imageBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    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"

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(prompt),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("weather.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day"}
    ],
    "tools": [{"type": "google_search"}],
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "aspect_ratio": "16:9"
    }
  }'
نمودار آب‌وهوای پنج روزه سان‌فرانسیسکو با هوش مصنوعی
جدول آب‌وهوای پنج روزه تولیدشده با هوش مصنوعی برای سانفرانسیسکو

پاسخ شامل google_search_call و google_search_result مرحله است، به‌همراه url_citation حاشیه‌نویسی به‌خط در مرحله نوشتاری:

  • google_search_result: حاوی search_suggestions، تکه‌کد HTML برای پرداز کردن پیشنهادهای جستجو در رابط کاربری شما است.
  • url_citation حاشیه‌نویسی: استنادهای به‌خط در مرحله نوشتار که بخش‌های پاسخ را به منابع وب آن‌ها پیوند می‌دهد.

«زمینه‌سازی با جستجوی تصویر Google» به مدل‌ها امکان می‌دهد از تصاویر وب که ازطریق «جستجوی تصویر Google» بازیابی شده‌اند به‌عنوان بافت تصویری برای تولید تصویر استفاده کنند. «جستجوی تصویر» نوع جدیدی از جستجو در ابزار موجود «پایه‌گذاری با جستجوی Google» است که در کنار جستجوی وب استاندارد عمل می‌کند.

برای فعال کردن «جستجوی تصویر»، ابزار google_search را در درخواست API پیکربندی کنید و image_search را در آرایه search_types مشخص کنید. «جستجوی تصویر» می‌تواند به‌طور مستقل یا همراه با «جستجوی وب» استفاده شود.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A detailed painting of a Timareta butterfly resting on a flower",
    tools=[{
      "type": "google_search",
      "search_types": ["web_search", "image_search"]
    }]
)

JavaScript

import { GoogleGenAI } from "@google/genai";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A detailed painting of a Timareta butterfly resting on a flower",
    tools: [{
      "type": "google_search",
      "search_types": ["web_search", "image_search"]
    }]
  });
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.GoogleSearchSearchType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;

Client client = new Client();

GoogleSearch searchTool =
    GoogleSearch.builder()
        .searchTypes(
            Arrays.asList(
                GoogleSearchSearchType.WEB_SEARCH, GoogleSearchSearchType.IMAGE_SEARCH))
        .build();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A detailed painting of a Timareta butterfly resting on a flower"))
        .tools(Arrays.asList(searchTool))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

رفتن

package main

import (
    "context"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    searchTool := interactions.GoogleSearch{
        SearchTypes: []interactions.GoogleSearchSearchType{
            interactions.GoogleSearchSearchTypeWebSearch,
            interactions.GoogleSearchSearchTypeImageSearch,
        },
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A detailed painting of a Timareta butterfly resting on a flower"),
            Tools: []interactions.Tool{
                interactions.NewTool(searchTool),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    _ = res
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A detailed painting of a Timareta butterfly resting on a flower",
    "tools": [{"type": "google_search", "search_types": ["web_search", "image_search"]}]
  }'

الزامات نمایشگر

وقتی از «جستجوی تصویر» در «زمینه با جستجوی Google» استفاده می‌کنید، باید search_suggestions را از مرحله google_search_result نمایش دهید. الزامات کامل استفاده در شرایط خدمات به‌تفصیل شرح داده شده است.

پاسخ

برای پاسخ‌های مستند بااستفاده از جستجوی تصویر، API استنادهای درون‌خطی و فراداده‌های ارجاع را به‌عنوان بخشی از مراحل پاسخ برمی‌گرداند:

  • ‫url_citation گزارمان: استنادهای به‌خط در بلوک محتوای نوشتاری در model_output، که محتوای تولیدشده را به منبع آن پیوند می‌دهد.

  • google_search_result: حاوی search_suggestions، یک گزیده HTML برای پرداز کردن پیشنهادهای جستجو در واسط کاربر شما.

تولید تصویر از ویدیو (Nano Banana 2.1،‏ 3.1 Flash، و 3.1 Flash Lite)

تولید تصویر از ویدیو به شما امکان می‌دهد بااستفاده از زمینه ویدیو به‌عنوان مرجع چندحالته، تصاویر جدیدی تولید کنید. این برای ایجاد ریزعکس‌های ویدیویی با کیفیت بالا، پوسترهای سینمایی، اطلاع‌نگاشت‌های خلاصه، یا آثار هنری جدید الهام‌گرفته از یک صحنه ویدیو مفید است.

درطول تولید، مدل قاب‌های ویدیو را در بافت تجزیه‌وتحلیل می‌کند تا زمینه‌های بصری و رویدادهای کلیدی را استخراج کند، سپس از آن‌ها درکنار پیام‌واره نوشتاری شما برای ترکیب کردن تصویر برونداد استفاده می‌کند.

می‌توانید نشانی‌های وب YouTube عمومی را مستقیماً در درخواست API خود بگذرانید یا فایل‌های ویدیویی محلی را بااستفاده از Files API بارگذاری کنید.

Python

from google import genai
from google.genai import types
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "video",
            "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",
            "mime_type": "video/mp4"
        },
        {"type": "text", "text": "Generate a poster image that captures the key themes of this video."}
    ],
    response_format={"type": "image", "aspect_ratio": "16:9"}
)

# Save the generated image part
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("video_poster.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))
                print("Image saved as video_poster.png")

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: [
      {
        type: "video",
        uri: "https://www.youtube.com/watch?v=UTdfxFyOQTI",
        mime_type: "video/mp4"
      },
      { type: "text", text: "Generate a poster image that captures the key themes of this video." }
    ],
    response_format: {
      type: "image",
      aspect_ratio: "16:9"
    }
  });

  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("video_poster.png", buffer);
          console.log("Image saved as video_poster.png");
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

Content videoContent =
    VideoContent.builder()
        .uri("https://www.youtube.com/watch?v=UTdfxFyOQTI")
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();
Content textContent =
    TextContent.builder()
        .text("Generate a poster image that captures the key themes of this video.")
        .build();

List contents = Arrays.asList(videoContent, textContent);

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content block : outputStep.content().get()) {
          if (block instanceof TextContent) {
            System.out.println(((TextContent) block).text().orElse(""));
          } else if (block instanceof ImageContent) {
            ImageContent img = (ImageContent) block;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("video_poster.png"), imgBytes);
              System.out.println("Image saved as video_poster.png");
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    contents := []interactions.Content{
        interactions.NewContent(interactions.VideoContent{
            URI:      genai.Ptr("https://www.youtube.com/watch?v=UTdfxFyOQTI"),
            MimeType: interactions.VideoContentMimeTypeVideoMp4.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: "Generate a poster image that captures the key themes of this video.",
        }),
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(contents),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, block := range step.ModelOutputStep.Content {
                if block.TextContent != nil {
                    fmt.Println(block.TextContent.Text)
                } else if block.ImageContent != nil && block.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*block.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("video_poster.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                    fmt.Println("Image saved as video_poster.png")
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {
        "type": "video",
        "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",
        "mime_type": "video/mp4"
      },
      {
        "type": "text",
        "text": "Generate a poster image that captures the key themes of this video."
      }
    ],
    "response_format": {
      "type": "image",
      "aspect_ratio": "16:9"
    }
  }'
اطلاع‌نگاشت تولیدشده با هوش مصنوعی از ویدیو YouTube
اینفوگرافیک تولیدشده با هوش مصنوعی از ویدیو YouTube

تولید تصاویر با وضوح حداکثر 4K

مدل‌های تصویر Gemini 3 به‌طور پیش‌فرض ۱ هزار تصویر تولید می‌کنند اما می‌توانند تصاویر ۲ هزار، ۴ هزار، و ۵۱۲ پیکسل (۰٫۵ هزار) (فقط تصویر Gemini 3.1 Flash) نیز تولید کنند. برای تولید دارایی‌های با وضوح بالاتر، image_size را در response_format مشخص کنید.

باید از حرف بزرگ «K» استفاده کنید (برای نمونه، 512px (05.K)،‏ 1K،‏ 2K،‏ 4K). پارامترهای حروف کوچک (برای نمونه، 1k) رد خواهد شد.

Python

from google import genai
from google.genai import types
import base64

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."

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=prompt,
    response_format={
        "type": "image",
        "mime_type": "image/jpeg",
        "aspect_ratio": "1:1",
        "image_size": "1K"
    },
)

print(interaction.output_text)

with open("butterfly.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.",
    response_format: {
      type: "image",
      mime_type: "image/png",
      aspect_ratio: "1:1",
      image_size: "1K",
    },
  });

  console.log(interaction.output_text);

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('butterfly.png', buffer);
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

String 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.";

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                .aspectRatio(ImageResponseFormatAspectRatio.of("1:1"))
                .imageSize(ImageResponseFormatImageSize.ONE_K)
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.of(prompt))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("butterfly.png"), imageBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    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."

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("1:1").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeOneK.ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(prompt),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("butterfly.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.",
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "aspect_ratio": "1:1",
      "image_size": "1K"
    }
  }'

تصویر زیر نمونه‌ای از تصویر تولیدشده از این پیام‌واره است:

طرح آناتومی به‌سبک داوینچی که با هوش مصنوعی از پروانه شهریار تشریح‌شده تولید شده است.
طرح آناتومی پروانه شهریار به سبک داوینچی که با هوش مصنوعی تولید شده است.

روند تفکر

مدل‌های تصویر Gemini 3 مدل‌های تفکری هستند که برای پیام‌واره‌های پیچیده از فرایند استدلال («اندیشگر») استفاده می‌کنند. این ویژگی به‌طور پیش‌فرض فعال است و نمی‌تواند در «میانای برنامه‌سازی کاربردی» غیرفعال شود. برای کسب اطلاعات بیشتر درباره فرایند تفکر، به راهنمای تفکر Gemini مراجعه کنید.

این مدل حداکثر دو تصویر موقت تولید می‌کند تا ترکیب‌بندی و منطق را آزمایش کند. آخرین تصویر در «درحال فکر کردن» همان تصویر نهایی پردازش‌شده است.

می‌توانید افکاری را که منجر به تولید تصویر نهایی شده است بررسی کنید.

Python

for step in interaction.steps:
    if step.type == "thought":
        for content_block in step.summary:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                image = Image.open(io.BytesIO(base64.b64decode(content_block.data)))
                image.show()

JavaScript

for (const step of interaction.steps) {
  if (step.type === "thought") {
    for (const contentBlock of step.summary) {
      if (contentBlock.type === "text") {
        console.log(contentBlock.text);
      } else if (contentBlock.type === "image") {
        const buffer = Buffer.from(contentBlock.data, 'base64');
        fs.writeFileSync('thought_image.png', buffer);
      }
    }
  }
}

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.ThoughtStep;
import com.google.genai.gaos.models.interactions.ThoughtSummaryContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A futuristic city built inside a giant glass bottle floating in space"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ThoughtStep) {
      ThoughtStep thoughtStep = (ThoughtStep) step;
      if (thoughtStep.summary().isPresent()) {
        for (ThoughtSummaryContent contentBlock : thoughtStep.summary().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("thought_image.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A futuristic city built inside a giant glass bottle floating in space"),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ThoughtStep != nil {
            for _, contentBlock := range step.ThoughtStep.Summary {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("thought_image.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

نوشتار و تصاویر درهم‌تنیده

درحالی‌که مدل‌های استاندارد تولید تصویر فقط تصویر تولید می‌کنند، برخی‌از مدل‌های پیشرفته Gemini 3 (مثل gemini-3-pro-image) می‌توانند محتوای درهم‌آمیخته تولید کنند—مثل داستان‌ها یا راهنمای آموزشی که هم شامل بلوک‌های نوشتاری و هم تصویرسازی در یک پاسخ است.

ازآنجایی‌که برونداد پیچیده و درهم‌آمیخته است، ویژگی‌های راحتی مثل .output_image یا .output_text کل توالی را ضبط نخواهند کرد. برای دسترسی به و ذخیره محتوای درهم‌آمیخته، باید به‌طور دستی روی steps تکرار کنید:

Python

interaction = client.interactions.create(
    model="gemini-3-pro-image",
    input="Write the story of the lifecycle of a monarch butterfly, interleave illustrations",
)

image_counter = 1
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                filename = f"butterfly_lifecycle_{image_counter}.png"
                with open(filename, "wb") as f:
                    f.write(base64.b64decode(content_block.data))
                print(f"\n[Saved illustration: {filename}]\n")
                image_counter += 1

JavaScript

const interaction = await ai.interactions.create({
    model: "gemini-3-pro-image",
    input: "Write the story of the lifecycle of a monarch butterfly, interleave illustrations",
});

let imageCounter = 1;
for (const step of interaction.steps) {
  if (step.type === "model_output") {
    for (const contentBlock of step.content) {
      if (contentBlock.type === "text") {
        console.log(contentBlock.text);
      } else if (contentBlock.type === "image") {
        const buffer = Buffer.from(contentBlock.data, "base64");
        const filename = `butterfly_lifecycle_${imageCounter}.png`;
        fs.writeFileSync(filename, buffer);
        console.log(`\n[Saved illustration: ${filename}]\n`);
        imageCounter++;
      }
    }
  }
}

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3-pro-image"))
        .input(
            InteractionsInput.of(
                "Write the story of the lifecycle of a monarch butterfly, interleave illustrations"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

int imageCounter = 1;
if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              String filename = String.format("butterfly_lifecycle_%d.png", imageCounter);
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get(filename), imgBytes);
              System.out.printf("%n[Saved illustration: %s]%n", filename);
              imageCounter++;
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3-pro-image"),
            Input: interactions.NewInteractionsInput("Write the story of the lifecycle of a monarch butterfly, interleave illustrations"),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    imageCounter := 1
    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    filename := fmt.Sprintf("butterfly_lifecycle_%d.png", imageCounter)
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile(filename, imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                    fmt.Printf("\n[Saved illustration: %s]\n", filename)
                    imageCounter++
                }
            }
        }
    }
}

کنترل سطوح اندیشیدن

با Gemini Nano Banana 2.1،‏ Gemini 3.1 Flash Image، و Gemini 3.1 Flash Lite Image، می‌توانید میزان تفکری را که مدل برای ایجاد تعادل بین کیفیت و تأخیر استفاده می‌کند کنترل کنید:

مدل سطوح پشتیبانی‌شده اندیشیدن پیش‌فرض
Gemini Nano Banana 2.1 minimal، medium، high medium
تصویر Gemini 3.1 Flash ‫minimal،‏ high minimal
تصویر Gemini 3.1 Flash Lite ‫minimal،‏ high minimal

Python

from google import genai
from PIL import Image
import base64
import io

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A futuristic city built inside a giant glass bottle floating in space",
    generation_config={"thinking_level": "high"},
)

print(interaction.output_text)

image = Image.open(io.BytesIO(base64.b64decode(interaction.output_image.data)))

image.show()

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A futuristic city built inside a giant glass bottle floating in space",
    generation_config: { thinking_level: "high" },
  });

  console.log(interaction.output_text);

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('image.png', buffer);
}
main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GenerationConfig;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ThinkingLevel;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A futuristic city built inside a giant glass bottle floating in space"))
        .generationConfig(GenerationConfig.builder().thinkingLevel(ThinkingLevel.HIGH).build())
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("futuristic_city.png"), imageBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A futuristic city built inside a giant glass bottle floating in space"),
            GenerationConfig: &interactions.GenerationConfig{
                ThinkingLevel: interactions.ThinkingLevelHigh.ToPointer(),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("futuristic_city.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A futuristic city built inside a giant glass bottle floating in space",
    "generation_config": {
      "thinking_level": "high"
    }
  }'

توجه داشته باشید که هزینه توکن‌های تفکر به‌طور پیش‌فرض برای مدل‌های تفکر محاسبه می‌شود، زیرا فرایند تفکر همیشه به‌طور پیش‌فرض اتفاق می‌افتد، چه این فرایند را مشاهده کنید چه نکنید.

سایر حالت‌های تولید تصویر

اگرچه مدل‌های تولید تصویر Nano Banana برای اکثر موارد استفاده توصیه می‌شود، می‌توانید مدل‌های تولید تصویر اختصاصی را نیز کاوش کنید:

  • Imagen: مدل‌های قدیمی نوشتار به تصویر Google (متوقف شده است).
  • Veo: مدل تولید ویدیو Google.

تولید تصویر به‌صورت دسته‌ای

همه قابلیت‌های تولید تصویر که در این صفحه توضیح داده شده است را می‌توان بااستفاده از Batch API به‌عنوان کار دسته‌ای اجرا کرد. این روش برای زمانی که نیاز به تولید تصاویر زیادی دارید ایده‌آل است. درازای زمان پاسخ‌دهی حداکثر ۲۴ ساعته، حدود نرخ بالاتری دریافت می‌کنید.

راهنمای پیام‌واره و استراتژی‌ها

این بخش نمونه‌های پیام‌واره و الگوهایی برای گردش‌های کار رایج تولید تصویر و ویرایش ارائه می‌دهد. هر نمونه شامل یک قالب قابل استفاده مجدد و یک پیام‌واره نمونه برای «میانای برنامه‌سازی کاربردی تعاملات» است.

پیام‌واره‌های تولید تصویر

مثال‌های زیر نشان می‌دهد که چگونه از پیام‌واره‌های نوشتاری برای تولید انواع مختلف تصاویر استفاده کنید.

۱. صحنه‌های واقع‌نما

صحنه‌ای را با جزئیات کامل توصیف کنید. هرچه دقیق‌تر باشید، کنترل بیشتری بر نتایج خواهید داشت.

الگو

A photorealistic [type of shot] of a [subject description] in a [setting
description]. [Description of the light]. Shot from a [camera angle]
with a [lens type].

پیام‌واره

A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.

Python

from google import genai
from google.genai import types
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",
    response_format=[
        {
            "type": "image",
            "mime_type": "image/jpeg",
            "aspect_ratio": "16:9",
        }
    ],
)

print(interaction.output_text)

with open("coral_reef.png", "wb") as f:

    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",
    response_format: [
      {
        type: "image",
        mime_type: "image/jpeg",
        aspect_ratio: "16:9",
      }
    ],
  });
  console.log(interaction.output_text);

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('coral_reef.png', buffer);
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        Arrays.asList(
            ResponseFormat.of(
                ImageResponseFormat.builder()
                    .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                    .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                    .build())));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9."))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("coral_reef.png"), imageBytes);
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    format := interactions.NewCreateModelInteractionResponseFormat([]interactions.ResponseFormat{
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    })

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput("A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9."),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("coral_reef.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",
    "response_format": {
      "type": "image",
      "mime_type": "image/png",
      "aspect_ratio": "16:9"
    }
  }'

۲. مصورسازی‌ها و برچسب‌های سبک‌دارشده

سبک هنری، موضوع، و رسانه را توصیف کنید. برای دریافت نتایج یکپارچه، درباره جزئیات دیداری (خطوط پررنگ، رنگ‌ها، و غیره) دقیق باشید.

الگو

A [style] of a [subject, with details about accessories or actions]
doing [activity]. The design features [visual qualities, e.g., bold outlines,
cel-shading, etc.] and [color/background preference].

پیام‌واره

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.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.",
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("red_panda_sticker.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It's munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.",
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("red_panda_sticker.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "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."))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("red_panda_sticker.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("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."),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("red_panda_sticker.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It is munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white."
  }'
چسبانقش به‌سبک «کاویایی» از یک قرمز خوشحال…
چسبانقش کاوایی از یک پاندای سرخ خوشحال…

۳. نوشتار دقیق در تصاویر

‫Gemini در پرداز کردن نوشتار برتری دارد. درباره نوشتار، سبک قلم (توصیفی)، و طراحی کلی واضح باشید. از «تصویر Gemini 3 Pro» برای تولید دارایی حرفه‌ای استفاده کنید.

الگو

Create a [image type] for [brand/concept] with the text "[text to render]"
in a [font style]. The design should be [style description], with a
[color scheme].

پیام‌واره

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.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",
    response_format={"type": "image", "aspect_ratio": "1:1"},
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("logo_example.jpg", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Create a modern, minimalist logo for a coffee shop called 'The Daily Grind'. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",
    response_format: { type: "image", aspect_ratio: "1:1" },
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("logo_example.jpg", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("1:1"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "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."))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("logo_example.jpg"), imgBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("1:1").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput("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."),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("logo_example.jpg", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Create a modern, minimalist logo for a coffee shop called The Daily Grind. The text should be in a clean, bold, sans-serif font. The color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",
    "response_format": {
      "type": "image",
      "aspect_ratio": "1:1"
    }
  }'
نشان‌واره‌ای مدرن و کمینه‌گرا برای قهوه‌سرایی به‌نام «The Daily Grind» بساز…
نشان‌واره‌ای مدرن و کمینه‌گرا برای قهوه‌سرایی به‌نام «The Daily Grind» بساز…

۴. پیش‌نمونه‌های محصول و عکاسی تجاری

برای ایجاد عکس‌های محصول حرفه‌ای و تمیز برای تجارت الکترونیک، تبلیغات، یا نمانام‌سازی عالی است.

الگو

A high-resolution, studio-lit product photograph of a [product description]
on a [background surface/description]. The lighting is a [lighting setup,
e.g., three-point softbox setup] to [lighting purpose]. The camera angle is
a [angle type] to showcase [specific feature]. Ultra-realistic, with sharp
focus on [key detail]. [Aspect ratio].

پیام‌واره

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.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.",
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("product_mockup.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.",
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("product_mockup.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "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."))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("product_mockup.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("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."),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("product_mockup.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image."
  }'
عکس محصول با وضوح بالا و نورپردازی آتلیه‌ای از لیوان قهوه سرامیکی مینیمالیستی…
عکس محصول با وضوح بالا و نورپردازی استودیویی از لیوان قهوه سرامیکی ساده‌گرایانه…

۵. طراحی کمینه‌گرا و فضای منفی

برای ایجاد پس‌زمینه‌های وب‌سایت‌ها، ارائه‌ها، یا مواد بازاریابی که نوشتار روی آن‌ها قرار می‌گیرد عالی است.

الگو

A minimalist composition featuring a single [subject] positioned in the
[bottom-right/top-left/etc.] of the frame. The background is a vast, empty
[color] canvas, creating significant negative space. Soft, subtle lighting.
[Aspect ratio].

پیام‌واره

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.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.",
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("minimalist_design.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.",
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("minimalist_design.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "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."))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("minimalist_design.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("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."),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("minimalist_design.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image."
  }'
ترکیب‌بندی کمینه‌گرایانه‌ای که در آن یک برگ افرای قرمز ظریف به‌تنهایی به‌نمایش گذاشته شده است…
ترکیب‌بندی کمینه‌گرایانه‌ای که در آن یک برگ افرای قرمز ظریف به‌نمایش گذاشته شده است…

‫۶. هنر متوالی (قاب داستان مصور / داستان‌نما)

با تکیه بر ثبات شخصیت و توصیف صحنه، پانل‌هایی برای داستان‌سرایی تصویری ایجاد می‌کند. برای دقت در متن و توانایی داستان‌سرایی، این پیام‌واره‌ها با Gemini 3 Pro و Gemini 3.1 Flash Image بهترین عملکرد را دارند.

الگو

Make a 3 panel comic in a [style]. Put the character in a [type of scene].

پیام‌واره

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.

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:
    image_bytes = f.read()
text_input = "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene."

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {"type": "text", "text": text_input},
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/jpeg"
        }
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("comic_panel.jpg", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath = "/path/to/your/man_in_white_glasses.jpg";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  const input = [
    { type: "text", text: "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene." },
    {
      type: "image",
      mime_type: "image/jpeg",
      data: base64Image
    },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("comic_panel.jpg", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/man_in_white_glasses.jpg"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "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.";

Content textContent = TextContent.builder().text(textInput).build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_JPEG)
        .build();

List contents = Arrays.asList(textContent, imageContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("comic_panel.jpg"), outBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    imageBytes, err := os.ReadFile("/path/to/your/man_in_white_glasses.jpg")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "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."

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImageJpeg.ToPointer(),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("comic_panel.jpg", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene."},
      {"type": "image", "data": "", "mime_type": "image/jpeg"}
    ]
  }'

ورودی

خروجی

مردی با عینک سفید
تصویر ورودی
داستان مصوری ۳ پانلی به‌سبک هنری خشن و نوآر بساز…
یک داستان مصور ۳ قاب در سبک هنری خشن و نوآر بساز…

از «جستجوی Google» برای تولید تصاویر براساس اطلاعات اخیر یا هم‌زمان استفاده کنید. این ویژگی برای اخبار، آب‌وهوا، و دیگر موضوعات حساس به زمان مفید است.

پیام‌واره

Make a simple but stylish graphic of last night's Arsenal game in the Champion's League

Python

from google import genai
from google.genai import types
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",
    tools=[{"type": "google_search"}],
    response_format={"type": "image", "aspect_ratio": "16:9"},
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("football-score.jpg", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",
    tools: [{ type: "google_search" }],
    response_format: { type: "image", aspect_ratio: "16:9", image_size: "2K" },
  });

  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("football-score.jpg", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Make a simple but stylish graphic of last night's Arsenal game in the Champion's League"))
        .tools(Arrays.asList(new GoogleSearch()))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("football-score.jpg"), imgBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("Make a simple but stylish graphic of last night's Arsenal game in the Champion's League"),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("football-score.jpg", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Make a simple but stylish graphic of last nights Arsenal game in the Champions League",
    "tools": [{"type": "google_search"}],
    "response_format": {
      "type": "image",
      "aspect_ratio": "16:9"
    }
  }'
گرافیک تولیدشده با هوش مصنوعی از امتیاز فوتبال آرسنال
گرافیک تولیدشده با هوش مصنوعی از نتیجه فوتبال آرسنال

پیام‌واره‌های ویرایش تصویر

این مثال‌ها نشان می‌دهد که چگونه برای ویرایش، ترکیب‌بندی، و انتقال سبک، تصاویر را در کنار پیام‌واره‌های نوشتاری خود ارائه دهید.

۱. افزودن و برداشتن عناصر

تصویری ارائه دهید و تغییرتان را شرح دهید. این مدل با سبک، نورپردازی، و پرسپکتیو تصویر اصلی مطابقت خواهد داشت.

الگو

Using the provided image of [subject], please [add/remove/modify] [element]
to/from the scene. Ensure the change is [description of how the change should
integrate].

پیام‌واره

"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."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/cat_photo.png', 'rb') as f:
    image_bytes = f.read()
text_input = """Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {"type": "text", "text": text_input},
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        }
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("cat_with_hat.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath = "/path/to/your/cat_photo.png";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  const input = [
    { type: "text", text: "Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off." },
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image
    },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("cat_with_hat.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/cat_photo.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off.";

Content textContent = TextContent.builder().text(textInput).build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();

List contents = Arrays.asList(textContent, imageContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("cat_with_hat.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    imageBytes, err := os.ReadFile("/path/to/your/cat_photo.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off."

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("cat_with_hat.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
            {\"type\": \"text\", \"text\": \"Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off.\"},
            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"}
        ]
    }"

ورودی

خروجی

تصویر واقع‌نمای گربه زنجبیلی پشمالو..
تصویری واقع‌نما از گربه پشمالوی زنجبیلی…
بااستفاده از تصویر گربه‌ام که ارائه شده است، لطفاً کلاه جادوگری بافتنی کوچکی اضافه کن…
بااستفاده از تصویر گربه‌ام که ارائه شده است، لطفاً کلاه جادوگری کوچک و بافتنی اضافه کن…

۲. رنگ‌آمیزی مجدد (پوشاندن معنایی)

با تعریف مکالمه‌ای «پوشش»، بخش خاصی از تصویر را ویرایش کنید و بقیه را دست‌نخورده باقی بگذارید.

الگو

Using the provided image, change only the [specific element] to [new
element/description]. Keep everything else in the image exactly the same,
preserving the original style, lighting, and composition.

پیام‌واره

"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."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/living_room.png', 'rb') as f:
    image_bytes = f.read()
text_input = """Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("living_room_edited.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath = "/path/to/your/living_room.png";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  const input = [
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image
    },
    { type: "text", text: "Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged." },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("living_room_edited.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/living_room.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "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.";

Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List contents = Arrays.asList(imageContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("living_room_edited.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    imageBytes, err := os.ReadFile("/path/to/your/living_room.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "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."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("living_room_edited.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"},
        {\"type\": \"text\", \"text\": \"Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged.\"}
      ]
    }"

ورودی

خروجی

نمایی عریض از اتاق نشیمن مدرن و پرنور…
نمای عریضی از اتاق نشیمن مدرن و پرنور…
بااستفاده از تصویر اتاق نشیمن ارائه‌شده، فقط کاناپه آبی را به کاناپه چرمی قهوه‌ای کلاسیک چسترفیلد تغییر بده…
بااستفاده از تصویر ارائه‌شده از اتاق نشیمن، فقط مبل آبی را به مبل چرمی قهوه‌ای رنگ قدیمی چسترفیلد تغییر بده…

۳. انتقال سبک

تصویری ارائه دهید و از مدل بخواهید محتوای آن را با سبک هنری دیگری بازآفرینی کند.

الگو

Transform the provided photograph of [subject] into the artistic style of [artist/art style]. Preserve the original composition but render it with [description of stylistic elements].

پیام‌واره

"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."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/city.png', 'rb') as f:
    image_bytes = f.read()
text_input = """Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("city_style_transfer.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});
  const imageData = fs.readFileSync("/path/to/your/city.png");
  const base64Image = imageData.toString("base64");

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: [
      {
        type: "image",
        mime_type: "image/png",
        data: base64Image
      },
      { type: "text", text: "Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows." },
    ],
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("city_style_transfer.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/city.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "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.";

Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List contents = Arrays.asList(imageContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("city_style_transfer.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    imageBytes, err := os.ReadFile("/path/to/your/city.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "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."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("city_style_transfer.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"},
        {\"type\": \"text\", \"text\": \"Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows.\"}
      ]
    }"

ورودی

خروجی

عکس واقع‌گرایانه با وضوح بالا از خیابانی شلوغ در شهر…
عکس واقع‌گرایانه با وضوح بالا از خیابان شلوغ شهر…
عکس ارائه‌شده از خیابان شهری مدرن در شب را به… تبدیل کن
عکس ارائه‌شده از خیابان شهری مدرن در شب را به… تبدیل کن

۴. ترکیب‌بندی پیشرفته: ترکیب چندین تصویر

چندین تصویر به‌عنوان زمینه ارائه دهید تا صحنه ترکیبی جدیدی ایجاد کنید. این ویژگی برای پیش‌نمایش محصول یا کلاژهای خلاقانه عالی است.

الگو

Create a new image by combining the elements from the provided images. Take
the [element from image 1] and place it with/on the [element from image 2].
The final image should be a [description of the final scene].

پیام‌واره

"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."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/dress.png', 'rb') as f:
    dress_bytes = f.read()
with open('/path/to/your/model.png', 'rb') as f:
    model_bytes = f.read()
text_input = """Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "image",
            "data": base64.b64encode(dress_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(model_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("fashion_ecommerce_shot.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath1 = "/path/to/your/dress.png";
  const imageData1 = fs.readFileSync(imagePath1);
  const base64Image1 = imageData1.toString("base64");
  const imagePath2 = "/path/to/your/model.png";
  const imageData2 = fs.readFileSync(imagePath2);
  const base64Image2 = imageData2.toString("base64");

  const input = [
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image1
    },
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image2
    },
    { type: "text", text: "Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment." },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("fashion_ecommerce_shot.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] dressBytes = Files.readAllBytes(Paths.get("/path/to/your/dress.png"));
byte[] modelBytes = Files.readAllBytes(Paths.get("/path/to/your/model.png"));
String textInput =
    "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.";

Content dressContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(dressBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content modelContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(modelBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List contents = Arrays.asList(dressContent, modelContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("fashion_ecommerce_shot.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    dressBytes, err := os.ReadFile("/path/to/your/dress.png")
    if err != nil {
        log.Fatal(err)
    }
    modelBytes, err := os.ReadFile("/path/to/your/model.png")
    if err != nil {
        log.Fatal(err)
    }
    textInput := "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."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(dressBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(modelBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("fashion_ecommerce_shot.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"},
            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"},
            {\"type\": \"text\", \"text\": \"Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment.\"}
      }]
    }"

ورودی ۱

ورودی ۲

خروجی

پیراهن تابستانی گل‌دار آبی روی پس‌زمینه‌ای خنثی
پیراهن تابستانی گل‌دار آبی روی پس‌زمینه‌ای خنثی
عکس تمام‌قد از زنی با موهای جمع‌شده در پشت سر…
تک‌عکس تمام‌قد از زنی با موهای جمع‌شده در پشت سر…
زنی که پیراهن تابستانی گل‌دار آبی پوشیده است در فضای باز
زنی با پیراهن تابستانی گل‌دار آبی در فضای باز

۵. حفظ جزئیات با دقت بالا

برای اطمینان از اینکه جزئیات مهم (مانند چهره یا نشان‌واره) درطول ویرایش حفظ می‌شوند، آن‌ها را به‌همراه درخواست ویرایش خود با جزئیات کامل شرح دهید.

الگو

Using the provided images, place [element from image 2] onto [element from
image 1]. Ensure that the features of [element from image 1] remain
completely unchanged. The added element should [description of how the
element should integrate].

پیام‌واره

"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."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/woman.png', 'rb') as f:
    woman_bytes = f.read()
with open('/path/to/your/logo.png', 'rb') as f:
    logo_bytes = f.read()
text_input = """Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(woman_bytes).decode('utf-8')},
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(logo_bytes).decode('utf-8')},
      {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("woman_with_logo.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath1 = "/path/to/your/woman.png";
  const imageData1 = fs.readFileSync(imagePath1);
  const base64Image1 = imageData1.toString("base64");
  const imagePath2 = "/path/to/your/logo.png";
  const imageData2 = fs.readFileSync(imagePath2);
  const base64Image2 = imageData2.toString("base64");

  const input = [
    {"type": "image", "mime_type":"image/png", "data": base64Image1},
    {"type": "image", "mime_type":"image/png", "data": base64Image2},
    {"type": "text", "text": "Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."},
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("woman_with_logo.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] womanBytes = Files.readAllBytes(Paths.get("/path/to/your/woman.png"));
byte[] logoBytes = Files.readAllBytes(Paths.get("/path/to/your/logo.png"));
String textInput =
    "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.";

Content womanContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(womanBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content logoContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(logoBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List contents = Arrays.asList(womanContent, logoContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("woman_with_logo.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    womanBytes, err := os.ReadFile("/path/to/your/woman.png")
    if err != nil {
        log.Fatal(err)
    }
    logoBytes, err := os.ReadFile("/path/to/your/logo.png")
    if err != nil {
        log.Fatal(err)
    }
    textInput := "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."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(womanBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(logoBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("woman_with_logo.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"},
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"},
        {\"type\": \"text\", \"text\": \"Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt.\"}
      ]
    }"

ورودی ۱

ورودی ۲

خروجی

عکس پرسنلی حرفه‌ای از زنی با موهای قهوه‌ای و چشمان آبی…
عکس پرسنلی حرفه‌ای از زنی با موهای قهوه‌ای و چشمان آبی…
شناسه نمانام مدرن با حروف G و A
شناسه نمانام مدرن با حروف G و A
اولین تصویر زن با موهای قهوه‌ای، چشمان آبی، و چهره عادی را بگیر…
اولین تصویر از زن با موهای قهوه‌ای، چشمان آبی، و چهره‌ای خنثی را بگیر…

‫۶. به چیزی جان ببخشید

طرح یا نقاشی اولیه‌ای بارگذاری کنید و از مدل بخواهید آن را به تصویری تکمیل‌شده تبدیل کند.

الگو

Turn this rough [medium] sketch of a [subject] into a [style description]
photo. Keep the [specific features] from the sketch but add [new details/materials].

پیام‌واره

"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."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/car_sketch.png', 'rb') as f:
    sketch_bytes = f.read()
text_input = """Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(sketch_bytes).decode('utf-8')},
      {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("car_photo.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath = "/path/to/your/car_sketch.png";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  const input = [
    {"type": "image", "mime_type":"image/png", "data": base64Image},
    {"type": "text", "text": "Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."},
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("car_photo.png", buffer);
        }
      }
    }
  }
}

main();

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] sketchBytes = Files.readAllBytes(Paths.get("/path/to/your/car_sketch.png"));
String textInput =
    "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.";

Content sketchContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(sketchBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List contents = Arrays.asList(sketchContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("car_photo.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

رفتن

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    sketchBytes, err := os.ReadFile("/path/to/your/car_sketch.png")
    if err != nil {
        log.Fatal(err)
    }
    textInput := "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."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(sketchBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("car_photo.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"\"},
        {\"type\": \"text\", \"text\": \"Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting.\"}
      ]
    }"

ورودی

خروجی

طرح خودرو
طرح اولیه خودرو
برونداد نشان‌دهنده خودرو مفهومی نهایی
عکس صیقل‌داده‌شده از یک خودرو

‫۷. ثبات شخصیت: نمای ۳۶۰ درجه

با درخواست مکرر برای زاویه‌های مختلف می‌توانید نماهای ۳۶۰ درجه از یک شخصیت تولید کنید. برای بهترین نتیجه، تصویرهای تولیدشده قبلی را در پیام‌واره‌های بعدی بگنجانید تا یکپارچگی حفظ شود. برای ژست‌های پیچیده، تصویر مرجعی از ژست انتخاب‌شده ارائه دهید.

الگو

A studio portrait of [person] against [background], [looking forward/in profile looking right/etc.]

پیام‌واره

A studio portrait of this man against white, in profile looking right

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:
    image_bytes = f.read()
text_input = """A studio portrait of this man against white, in profile looking right"""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input={
      {"type": "text", "text": text_input},
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(image_bytes).decode('utf-8')}
    },
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("man_right_profile.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

ورودی

برونداد ۱

برونداد ۲

ورودی اصلی مردی با عینک سفید
تصویر اصلی
برونداد مردی با عینک سفید که به راست نگاه می‌کند
مردی با عینک سفید که به راست نگاه می‌کند
برونداد مردی با عینک سفید که به جلو نگاه می‌کند
مردی با عینک سفید که به جلو نگاه می‌کند

روال‌های مطلوب

برای اینکه نتایجتان را از خوب به عالی ارتقا دهید، این استراتژی‌های حرفه‌ای را در گردش کارتان بگنجانید.

  • بسیار دقیق باشید: هرچه جزئیات بیشتری ارائه دهید، کنترل بیشتری خواهید داشت. به‌جای «زره فانتزی»، آن را توصیف کنید: «زره صفحه‌ای پرآذین اِلفی، حکاکی‌شده با الگوهای برگ نقره‌ای، با یقه‌ای بلند و سرشانه‌هایی به‌شکل بال‌های شاهین.»
  • ارائه زمینه و هدف: هدف تصویر را توضیح دهید. درک مدل از زمینه بر برونداد نهایی تأثیر می‌گذارد. برای مثال، «نشان‌واره‌ای برای یک نمانام مراقبت از پوست ساده‌گرایانه و سطح بالا بساز» نتایج بهتری نسبت‌به «نشان‌واره‌ای بساز» خواهد داشت.
  • تکرار و پالایش: انتظار نداشته باشید که در اولین تلاش تصویر بی‌نقصی ایجاد کنید. از ماهیت مکالمه‌ای مدل برای ایجاد تغییرات کوچک استفاده کنید. با پیام‌واره‌هایی مثل «عالی است، اما می‌توانی نورپردازی را کمی گرم‌تر کنی؟» یا «همه چیز را همان‌طور نگه دار، اما حالت چهره شخصیت را جدی‌تر کن» ادامه بده.
  • استفاده از دستورالعمل‌های گام‌به‌گام: برای صحنه‌های پیچیده با عناصر زیاد، پیام‌واره خود را به مراحل تقسیم کنید. «ابتدا پس‌زمینه‌ای از جنگلی آرام و مه‌آلود در سپیده‌دم بساز. سپس، در پیش‌زمینه، محراب سنگی باستانی پوشیده‌شده از خزه اضافه کن. در آخر، شمشیری درخشان را روی قربانگاه قرار دهید."
  • از «پیام‌واره‌های منفی معنایی» استفاده کنید: به‌جای اینکه بگویید «بدون ماشین»، صحنه موردنظرتان را به‌صورت مثبت توصیف کنید: «خیابانی خالی و متروکه بدون هیچ نشانه‌ای از ترافیک.»
  • کنترل دوربین: از زبان عکاسی و سینمایی برای کنترل ترکیب استفاده کنید. عباراتی مثل wide-angle shot،‏ macro shot،‏ low-angle perspective.

محدودیت‌ها

  • برای بهترین عملکرد، از زبان‌های زیر استفاده کنید: 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.
  • تولید تصویر از ورودی‌های صوتی پشتیبانی نمی‌کند. ورودی‌های ویدیو فقط برای Gemini Nano Banana 2.1،‏ Gemini 3.1 Flash Image، و Gemini 3.1 Flash Lite Image پشتیبانی می‌شود.
  • مدل همیشه از تعداد دقیق بروندادهای تصویری که کاربر صریحاً درخواست می‌کند پیروی نمی‌کند.
  • ‫gemini-2.5-flash-image با حداکثر ۳ تصویر به‌عنوان ورودی بهترین عملکرد را دارد، درحالی‌که gemini-3-pro-image از ۵ تصویر با وفاداری بالا و در مجموع حداکثر ۱۴ تصویر پشتیبانی می‌کند. ‫gemini-nano-banana-2.1 و gemini-3.1-flash-image از شباهت نویسه تا ۴ نویسه و دقت تا ۱۰ شیء در یک گردش کار پشتیبانی می‌کنند.
  • وقتی برای تصویری نوشتار تولید می‌کنید، بهتر است ابتدا نوشتار را تولید کنید و سپس تصویری با آن نوشتار درخواست کنید تا Gemini بهترین عملکرد را داشته باشد.
  • درحال‌حاضر، gemini-nano-banana-2.1 و gemini-3.1-flash-image «پایه با جستجوی Google» از استفاده از تصاویر واقعی افراد از جستجوی وب پشتیبانی نمی‌کنند.
  • همه تصاویر تولیدشده حاوی ته‌نقش SynthID هستند.

پیکربندی‌های اختیاری

می‌توانید به‌صورت اختیاری قالب برونداد، نسبت ابعادی، و اندازه تصویر را بااستفاده از پارامتر response_format پیکربندی کنید.

قالب برونداد

مدل به‌طور پیش‌فرض هم پاسخ نوشتاری و هم پاسخ تصویری برمی‌گرداند. با مشخص کردن قالب تصویر در پارامتر response_format، می‌توانید پاسخ را پیکربندی کنید تا فقط تصاویر تولیدشده را برگرداند (نوشتار مکالمه‌ای را حذف کند).

برای درخواست چندوجهی (برای مثال، هم نوشتار و هم تصویر تولیدشده)، به‌جای آن آرایه‌ای از ورودی‌های قالب را به response_format ارسال کنید.

Python

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Write a short poem about a starry night and generate an image of it.",
    response_format=[
        {"type": "text"},
        {"type": "image"},
    ],
)

JavaScript

const interaction = await ai.interactions.create({
  model: "gemini-nano-banana-2.1",
  input: "Write a short poem about a starry night and generate an image of it.",
  response_format: [
    { type: "text" },
    { type: "image" },
  ],
});

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.TextResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        Arrays.asList(
            ResponseFormat.of(TextResponseFormat.builder().build()),
            ResponseFormat.of(ImageResponseFormat.builder().build())));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Write a short poem about a starry night and generate an image of it."))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

رفتن

package main

import (
    "context"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    format := interactions.NewCreateModelInteractionResponseFormat([]interactions.ResponseFormat{
        interactions.NewResponseFormat(interactions.TextResponseFormat{}),
        interactions.NewResponseFormat(interactions.ImageResponseFormat{}),
    })

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput("Write a short poem about a starry night and generate an image of it."),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    _ = res
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Write a short poem about a starry night and generate an image of it.",
    "response_format": [
      { "type": "text" },
      { "type": "image" }
    ]
  }'

نسبت ابعادی و اندازه تصویر

به‌طور پیش‌فرض، مدل اندازه تصویر برونداد را با اندازه تصویر ورودی شما مطابقت می‌دهد، یا درغیراین‌صورت مربع‌های ۱:۱ تولید می‌کند. وقتی type روی "image" تنظیم شده باشد، می‌توانید بااستفاده از فیلدهای aspect_ratio و image_size در بخش response_format، نسبت ابعادی و اندازه تصویر برونداد را کنترل کنید.

Python

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=prompt,
    response_format={
        "type": "image",
        "aspect_ratio": "16:9",
        "image_size": "2K",
    },
)

JavaScript

const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: prompt,
    response_format: {
      type: "image",
      aspect_ratio: "16:9",
      image_size: "2K",
    },
  });

جاوا

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();
String prompt = "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .imageSize(ImageResponseFormatImageSize.TWO_K)
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.of(prompt))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

رفتن

package main

import (
    "context"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    prompt := "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeTwoK.ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(prompt),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    _ = res
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",
    "response_format": {
      "type": "image",
      "aspect_ratio": "16:9",
      "image_size": "2K"
    }
  }'

نسبت‌های مختلف دردسترس و اندازه تصویر تولیدشده در جدول‌های زیر فهرست شده است:

Nano Banana 2.1

نسبت ابعادی وضوح 1K ‫۱ هزار داده‌واحد وضوح 2K ‫۲ هزار داده‌واحد وضوح 4K ‫۴ هزار داده‌واحد
۱:۱ ۱۰۲۴x۱۰۲۴ 1120 ‫۲۰۴۸×۲۰۴۸ 1680 ۴۰۹۶x۴۰۹۶ 2520
۱:۴ ‫۵۱۲×۲۰۴۸ 1120 ۱۰۲۴x۴۰۹۶ 1680 ‫۲۰۴۸x۸۱۹۲ 2520
۱:۸ ۳۸۴x۳۰۷۲ 1120 ۷۶۸x۶۱۴۴ 1680 ۱۵۳۶x۱۲۲۸۸ 2520
۲:۳ ۸۴۸x۱۲۶۴ 1120 ۱۶۹۶x۲۵۲۸ 1680 ۳۳۹۲x۵۰۵۶ 2520
‫۳:۲ ۱۲۶۴x۸۴۸ 1120 ۲۵۲۸x۱۶۹۶ 1680 ۵۰۵۶x۳۳۹۲ 2520
۳:۴ ‫۸۹۶×۱۲۰ 1120 ۱۷۹۲x۲۴۰۰ 1680 ۳۵۸۴x۴۸۰۰ 2520
۴:۱ ‫۲۰۴۸x۵۱۲ 1120 ۴۰۹۶x۱۰۲۴ 1680 ‫۸۱۹۲x۲۰۰۴۸ 2520
‫۴:۳ ۱۲۰۰x۸۹۶ 1120 ۲۴۰۰x۱۷۹۲ 1680 ۴۸۰۰x۳۵۸۴ 2520
۴:۵ ۹۲۸x۱۱۵۲ 1120 ۱۸۵۶x۲۳۰۴ 1680 ۳۷۱۲x۴۶۰۸ 2520
۵:۴ ۹۲۸x۱۱۵۲ 1120 ۱۸۵۶x۲۳۰۴ 1680 ۴۶۰۸x۳۷۱۲ 2520
۸:۱ ۳۰۷۲x۳۸۴ 1120 ۶۱۴۴x۷۶۸ 1680 ۱۵۳۶x۱۲۲۸۸ 2520
۹:۱۶ ۷۶۸x۱۳۷۶ 1120 ۱۵۳۶x۲۷۵۲ 1680 ۳۰۷۲x۵۵۰۴ 2520
۱۶:۹ ۷۶۸x۱۳۷۶ 1120 ۱۵۳۶x۲۷۵۲ 1680 ۳۰۷۲x۵۵۰۴ 2520
‫۲۱:۹ ۱۵۸۴x۶۷۲ 1120 ۳۱۶۸x۱۳۴۴ 1680 ۶۳۳۶x۲۶۸۸ 2520

‫3.1 Flash Image

نسبت ابعادی وضوح ۵۱۲ پیکسل ‫۰٫۵ هزار داده‌واحد وضوح 1K ‫۱ هزار داده‌واحد وضوح 2K ‫۲ هزار داده‌واحد وضوح 4K ‫۴ هزار داده‌واحد
۱:۱ ۵۱۲x۵۱۲ 747 ۱۰۲۴x۱۰۲۴ 1120 ‫۲۰۴۸×۲۰۴۸ 1680 ۴۰۹۶x۴۰۹۶ 2520
۱:۴ ‫۲۵۶x۱۰۲۴ 747 ‫۵۱۲×۲۰۴۸ 1120 ۱۰۲۴x۴۰۹۶ 1680 ‫۲۰۴۸x۸۱۹۲ 2520
۱:۸ ‫۱۹۲x۱۵۳۶ 747 ۳۸۴x۳۰۷۲ 1120 ۷۶۸x۶۱۴۴ 1680 ۱۵۳۶x۱۲۲۸۸ 2520
۲:۳ ۴۲۴x۶۳۲ 747 ۸۴۸x۱۲۶۴ 1120 ۱۶۹۶x۲۵۲۸ 1680 ۳۳۹۲x۵۰۵۶ 2520
‫۳:۲ ۶۳۲x۴۲۴ 747 ۱۲۶۴x۸۴۸ 1120 ۲۵۲۸x۱۶۹۶ 1680 ۵۰۵۶x۳۳۹۲ 2520
۳:۴ ۴۴۸x۶۰۰ 747 ‫۸۹۶×۱۲۰ 1120 ۱۷۹۲x۲۴۰۰ 1680 ۳۵۸۴x۴۸۰۰ 2520
۴:۱ ‫۱۰۲۴x۲۵۶ 747 ‫۲۰۴۸x۵۱۲ 1120 ۴۰۹۶x۱۰۲۴ 1680 ‫۸۱۹۲x۲۰۰۴۸ 2520
‫۴:۳ ‫۶۰۰x۴۴۸ 747 ۱۲۰۰x۸۹۶ 1120 ۲۴۰۰x۱۷۹۲ 1680 ۴۸۰۰x۳۵۸۴ 2520
۴:۵ ‫‎۴۶۴x۵۷۶ 747 ۹۲۸x۱۱۵۲ 1120 ۱۸۵۶x۲۳۰۴ 1680 ۳۷۱۲x۴۶۰۸ 2520
۵:۴ ‫۵۷۶x۴۶۴ 747 ۹۲۸x۱۱۵۲ 1120 ۱۸۵۶x۲۳۰۴ 1680 ۴۶۰۸x۳۷۱۲ 2520
۸:۱ ‫۱۹۲×۱۵۳۶ 747 ۳۰۷۲x۳۸۴ 1120 ۶۱۴۴x۷۶۸ 1680 ۱۵۳۶x۱۲۲۸۸ 2520
۹:۱۶ ۳۸۴x۶۸۸ 747 ۷۶۸x۱۳۷۶ 1120 ۱۵۳۶x۲۷۵۲ 1680 ۳۰۷۲x۵۵۰۴ 2520
۱۶:۹ ۶۸۸x۳۸۴ 747 ۷۶۸x۱۳۷۶ 1120 ۱۵۳۶x۲۷۵۲ 1680 ۳۰۷۲x۵۵۰۴ 2520
‫۲۱:۹ ۷۹۲x۱۶۸ 747 ۱۵۸۴x۶۷۲ 1120 ۳۱۶۸x۱۳۴۴ 1680 ۶۳۳۶x۲۶۸۸ 2520

‫3.1 Pro Image

نسبت ابعادی وضوح 1K ‫۱ هزار داده‌واحد وضوح 2K ‫۲ هزار داده‌واحد وضوح 4K ‫۴ هزار داده‌واحد
۱:۱ ۱۰۲۴x۱۰۲۴ 1120 ‫۲۰۴۸×۲۰۴۸ 1120 ۴۰۹۶x۴۰۹۶ 2000
۲:۳ ۸۴۸x۱۲۶۴ 1120 ۱۶۹۶x۲۵۲۸ 1120 ۳۳۹۲x۵۰۵۶ 2000
‫۳:۲ ۱۲۶۴x۸۴۸ 1120 ۲۵۲۸x۱۶۹۶ 1120 ۵۰۵۶x۳۳۹۲ 2000
۳:۴ ‫۸۹۶×۱۲۰ 1120 ۱۷۹۲x۲۴۰۰ 1120 ۳۵۸۴x۴۸۰۰ 2000
‫۴:۳ ۱۲۰۰x۸۹۶ 1120 ۲۴۰۰x۱۷۹۲ 1120 ۴۸۰۰x۳۵۸۴ 2000
۴:۵ ۹۲۸x۱۱۵۲ 1120 ۱۸۵۶x۲۳۰۴ 1120 ۳۷۱۲x۴۶۰۸ 2000
۵:۴ ۹۲۸x۱۱۵۲ 1120 ۱۸۵۶x۲۳۰۴ 1120 ۴۶۰۸x۳۷۱۲ 2000
۹:۱۶ ۷۶۸x۱۳۷۶ 1120 ۱۵۳۶x۲۷۵۲ 1120 ۳۰۷۲x۵۵۰۴ 2000
۱۶:۹ ۷۶۸x۱۳۷۶ 1120 ۱۵۳۶x۲۷۵۲ 1120 ۳۰۷۲x۵۵۰۴ 2000
‫۲۱:۹ ۱۵۸۴x۶۷۲ 1120 ۳۱۶۸x۱۳۴۴ 1120 ۶۳۳۶x۲۶۸۸ 2000

تصویر Gemini 2.5 Flash

نسبت ابعادی وضوح کدها
1:1 ۱۰۲۴x۱۰۲۴ 1290
2:3 ‫۸۳۲x۱۲۴۸ 1290
۳:۲ ۱۲۴۸x۸۳۲ 1290
۳:۴ ۸۶۴x۱۱۸۴ 1290
۴:۳ ۱۱۸۴x۸۶۴ 1290
‎۴:۵ ۸۹۶x۱۱۵۲ 1290
5:4 ۸۹۶x۱۱۵۲ 1290
۹:۱۶ ۷۶۸x۱۳۴۴ 1290
16:9 ‫۱۳۴۴x۷۶۸ 1290
21:9 ۶۷۲x۱۵۳۶ 1290

چه زمانی از Imagen استفاده کنیم

Imagen بسته شده است و دیگر ازطریق Gemini API دردسترس نیست. از Nano Banana برای تولید و ویرایش تصویر استفاده کنید.

قدم بعدی چیست

  • برای آشنایی با نحوه تولید ویدیو با Gemini API، راهنمای Veo را بررسی کنید.
  • برای کسب اطلاعات بیشتر درباره مدل‌های Gemini، به مدل‌های Gemini مراجعه کنید.