إنشاء الصور باستخدام Nano Banana

يمكنك إنشاء نماذج أولية لتطبيقات كاملة الوظائف وواجهات مستخدم متكاملة، والاطّلاع على Nano Banana 2 المدمج مع أدوات وبيانات واقعية ومنظومة Gemini المتكاملة. وكل ذلك قبل كتابة سطر واحد من الرموز البرمجية.
  • أو يمكنك إنشاء سلسلة إجراءات مخصّصة من خلال الطلبات:
  • مجلة london استعادة موزة مقهى مقالة كلب متساوي الأبعاد
  • مجلة
    تم الإنشاء بواسطة Nano Banana 2
    الطلب: "صورة لغلاف مجلة لامع، الغلاف الأزرق البسيط يحمل عبارة Nano Banana بخط عريض وكبير. النص مكتوب بخط serif ويملأ العرض. ولا أريد عرض أي نص آخر. أمام النص، تظهر صورة شخص يرتدي فستانًا أنيقًا وبسيطًا. وتحمل الرقم 2 بمرح، وهو نقطة التركيز.
    أضِف رقم العدد وتاريخ "فبراير 2026" في الزاوية مع رمز شريطي. تظهر المجلة على رفّ أمام جدار برتقالي مطلي بالجص داخل متجر مصمّم أزياء".
  • london
    تم الإنشاء بواسطة Nano Banana Pro
    الطلب: "أريد مشهدًا كرتونيًا ثلاثي الأبعاد مصغّرًا وواضحًا لمدينة لندن من منظور متساوي القياس (أيزومتري) وزاوية رؤية علوية 45 درجة، يضم أبرز معالمها وعناصرها المعمارية. استخدِم ملامس ناعمة ومصقولة مع مواد PBR واقعية وإضاءة وظلال لطيفة وواقعية. ادمج أحوال الطقس الحالية مباشرةً في بيئة المدينة لإنشاء أجواء غامرة. استخدِم تركيبة بسيطة وواضحة مع خلفية ناعمة بلون واحد. في أعلى الوسط، ضع العنوان "لندن" بنص غامق كبير، وأسفله رمز بارز للطقس، ثم التاريخ (نص صغير) ودرجة الحرارة (نص متوسط). يجب أن يكون النص بأكمله في المنتصف مع تباعد متسق، ويمكن أن يتداخل بشكل طفيف مع الأجزاء العلوية من المباني".
  • كيتزال
    تم الإنشاء بواسطة Nano Banana 2
    الطلب: "استخدِم البحث بالصور للعثور على صور دقيقة لطائر الكيتزال البرّاق. أريد إنشاء خلفية جميلة بنسبة عرض إلى ارتفاع 3:2 لهذا الطائر، مع تدرّج طبيعي من الأعلى إلى الأسفل وتصميم بسيط".
  • موزة
    تم الإنشاء بواسطة Nano Banana Pro
    الطلب: "أريد وضع هذا الشعار على إعلان راقٍ لعطر برائحة الموز. تم دمج الشعار بشكل مثالي في الزجاجة".
  • مقهى
    تم الإنشاء بواسطة Nano Banana Pro
    الطلب: "صورة لمشهد يومي في مقهى مزدحم يقدّم وجبة الفطور. في المقدّمة، يظهر رجل أنمي بشعر أزرق، وأحد الأشخاص هو رسم بقلم الرصاص، والآخر هو شخصية من الرسوم المتحركة بالطين"
  • مقالة
    تم الإنشاء بواسطة Nano Banana Pro
    الطلب: "استخدِم البحث لمعرفة ردود الفعل على إطلاق Gemini 3 Flash. استخدِم هذه المعلومات لكتابة مقالة قصيرة حول هذا الموضوع (مع عناوين). أريد صورة للمقالة كما ظهرت في مجلة لامعة تركّز على التصميم. تظهر في الصورة صفحة واحدة مطوية تعرض المقالة حول Gemini 3 Flash. صورة رئيسية واحدة Headline in serif."
  • كلب
    تم الإنشاء بواسطة Nano Banana Pro
    الطلب: "رمز يمثّل كلبًا لطيفًا. الخلفية بيضاء. اجعل الرموز بنمط ثلاثي الأبعاد ملوّن وملموس. لا يوجد نص".
  • متساوي الأبعاد
    تم الإنشاء بواسطة Nano Banana 2
    الطلب: "أريد إنشاء صورة متساوية القياس تمامًا. إنّها ليست صورة مصغّرة، بل صورة تم التقاطها من منظور متساوي القياس (أيزومتري) بشكل مثالي. إنّها صورة لحديقة حديثة جميلة. يظهر مسبح كبير على شكل الرقم 2 وعبارة: Nano Banana 2".

‫Nano Banana هو اسم إمكانات إنشاء الصور المضمّنة في Gemini. يمكن لـ Gemini إنشاء الصور ومعالجتها من خلال المحادثات باستخدام النصوص أو الصور أو الفيديوهات أو مزيج منها. يتيح لك ذلك إنشاء العناصر المرئية وتعديلها وتكرارها مع إمكانية تحكّم غير مسبوقة.

اختيار النموذج

يشير Nano Banana إلى النماذج التالية المتوفّرة في Gemini API:

  • ‫Nano Banana 2.1 (Gemini Nano Banana 2.1) (gemini-nano-banana-2.1): هو إصدار محدّث من Nano Banana 2، وهو النموذج الأساسي عالي الكفاءة لإنشاء الصور وتعديلها من خلال المحادثات. يحافظ هذا النموذج على سرعة Flash وكفاءته من حيث التكلفة، ويقدّم في الوقت نفسه جودة مرئية محسّنة وعرضًا أفضل للنصوص واتساقًا في المحادثات المتعددة الأدوار وتحسينًا في دقة المعلومات من خلال "بحث Google" بدقة 1K و2K و4K.
  • ‫Nano Banana 2 Lite (Gemini 3.1 Flash Lite Image) (gemini-3.1-flash-lite-image): هو نموذج Gemini الأسرع والأقل تكلفة لمعالجة الصور، وقد تم تصميمه ليكون سريعًا وقابلاً للتوسّع في الحالات التي تكون فيها السرعة والتكلفة هما القيود التشغيلية الأساسية. غير محسَّن لاستخدام عدة مراجع أو لإجراء تعديلات متسلسلة على دفعات
  • ‫Nano Banana 2 (Gemini 3.1 Flash Image) (gemini-3.1-flash-image): هو نموذج الجيل السابق العالي الكفاءة الذي يوازن بين السرعة وإنشاء الصور بدقة 4K والمعرفة العامة واتساق الصور المتعددة المراجع. ننصح باستخدام Nano Banana 2.1 في جميع المشاريع الجديدة.
  • ‫Nano Banana Pro (Gemini 3 Pro Image) (gemini-3-pro-image): هو الخيار المدفوع للمهام المرئية الأكثر تعقيدًا، ويوفّر أعلى مستوى من المعرفة العالمية، والترجمة المتقدّمة، والاتساق الدقيق مع العلامة التجارية، والتحكّم الإبداعي الدقيق.
  • ‫Nano Banana (Gemini 2.5 Flash Image) (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);
}

Go

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<Content> 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);
}

Go

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\": \"<BASE64_IMAGE_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);
}

Go

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);
}

Go

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": "<PREVIOUS_INTERACTION_ID>",
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "aspect_ratio": "16:9",
      "image_size": "2K"
    }
  }'
مخطّط بياني من إنشاء الذكاء الاصطناعي حول عملية البناء الضوئي باللغة الإسبانية
مخطّط بياني من إنشاء الذكاء الاصطناعي لعملية البناء الضوئي باللغة الإسبانية

ميزات Nano Banana

توفّر نماذج Nano Banana أحدث الميزات لإنشاء الصور وتعديلها. تم تحسين Nano Banana 2.1 وGemini 3.1 Flash Image لزيادة السرعة وحالات الاستخدام الكثيف، بينما تم تحسين Gemini 3 Pro Image لإنتاج مواد احترافية. تم تصميم هذه النماذج لتنفيذ أصعب مهام سير العمل من خلال الاستدلال المتقدّم، وهي تبرع في مهام الإنشاء والتعديل المعقّدة والمتعدّدة الخطوات.

  • صور عالية الدقة: إمكانات مدمجة لإنشاء صور بدقة 1K و2K و4K
    • يضيف Gemini 3.1 Flash Image دقة أصغر تبلغ 512 بكسل (0.5K) (غير متاحة في Gemini Nano Banana 2.1).
    • يتيح Gemini 3.1 Flash Lite Image دقة 1K فقط.
  • تكنولوجيا متقدمة لعرض النصوص: يمكنه إنشاء نصوص واضحة ومنسّقة للمخططات البيانية والقوائم والمخططات ومواد العرض التسويقية.
  • تحديد المصدر من خلال &quot;بحث Google&quot;: يمكن للنموذج استخدام &quot;بحث Google&quot; كأداة للتحقّق من الحقائق وإنشاء الصور استنادًا إلى البيانات في الوقت الفعلي (مثل خرائط الطقس الحالية والرسوم البيانية للأسهم والأحداث الأخيرة).
    • لا يتوفّر هذا الخيار في نموذج Gemini 3.1 Flash Lite Image.
    • يضيف ‫Gemini Nano Banana 2.1 وGemini 3.1 Flash Image ميزة دمج "صور بحث Google" المستندة إلى المصادر إلى جانب "بحث الويب".
  • وضع التفكير: يستخدم النموذج عملية "تفكير" للاستدلال على الطلبات المعقّدة. ينشئ النموذج "صورًا فكرية" مؤقتة (تظهر في الخلفية ولكن لا يتم تحصيل رسوم مقابلها) لتحسين التركيب قبل إنتاج النتيجة النهائية عالية الجودة.
  • ما يصل إلى 14 صورة مرجعية: يمكنك دمج ما يصل إلى 14 صورة مرجعية لإنشاء الصورة النهائية.
  • نسب عرض إلى ارتفاع جديدة: يضيف 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 كنسب عرض إلى ارتفاع.

استخدام ما يصل إلى 14 صورة مرجعية

تتيح لك نماذج Nano Banana دمج ما يصل إلى 14 صورة مرجعية. يمكن أن تتضمن هذه الصور الـ 14 ما يلي:

Gemini 3.1 Flash Lite Image ‫Gemini Nano Banana 2.1 وGemini 3.1 Flash Image Gemini 3 Pro Image
ما يصل إلى 14 صورة لعناصر عالية الدقة لتضمينها في الصورة النهائية ما يصل إلى 10 صور لعناصر عالية الدقة لتضمينها في الصورة النهائية ما يصل إلى 6 صور لعناصر عالية الدقة لتضمينها في الصورة النهائية
لا ينطبق ما يصل إلى 4 صور لشخصيات للحفاظ على الاتساق في مظهر الشخصية ما يصل إلى 5 صور لشخصيات للحفاظ على الاتساق في مظهر الشخصية
لا ينطبق لا ينطبق ما يصل إلى 3 صور لاستخدامها كمراجع للنمط

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<Content> 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);
}

Go

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\": \"<BASE64_DATA_IMG_1>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_2>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_3>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_4>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_5>\"}
      ],
      \"response_format\": {
        \"type\": \"image\",
        \"aspect_ratio\": \"5:4\",
        \"image_size\": \"2K\"
      }
    }"
صورة جماعية في المكتب من إنشاء الذكاء الاصطناعي
صورة جماعية في المكتب من إنشاء الذكاء الاصطناعي

تحديد المصدر من خلال "بحث Search"

استخدِم أداة &quot;بحث Google&quot; لإنشاء صور من إنشاء الذكاء الاصطناعي التوليدي استنادًا إلى معلومات في الوقت الفعلي، مثل توقّعات الطقس أو الرسوم البيانية للأسهم أو الأحداث الأخيرة.

يُرجى العِلم أنّه عند استخدام ميزة &quot;الربط ببحث Google&quot; مع إنشاء الصور، لا يتم تمرير نتائج البحث المستندة إلى الصور إلى نموذج الإنشاء ويتم استبعادها من الردّ (يُرجى الاطّلاع على الربط ببحث الصور من 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);
}

Go

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" كسياق مرئي لإنشاء الصور. "البحث بالصور" هو نوع بحث جديد ضمن أداة "تحديد المصدر من خلال بحث Search" الحالية، ويعمل إلى جانب بحث الويب العادي.

لتفعيل ميزة "البحث بالصور"، اضبط أداة google_search في طلب البيانات من واجهة برمجة التطبيقات وحدِّد 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();

Go

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. يمكنك الاطّلاع على متطلبات الاستخدام الكاملة في بنود الخدمة.

الردّ

بالنسبة إلى الردود المستندة إلى مصادر موثوقة باستخدام البحث بالصور، تعرض واجهة برمجة التطبيقات الاقتباسات المضمّنة والبيانات الوصفية الخاصة بالإحالة كجزء من خطوات الردّ:

  • التعليقات التوضيحية url_citation: هي اقتباسات مضمّنة في مجموعة المحتوى النصي ضمن model_output، وتربط المحتوى الذي تم إنشاؤه بمصدره.

  • google_search_result: يحتوي على search_suggestions، وهو مقتطف HTML لعرض اقتراحات البحث في واجهة المستخدم.

تحويل الفيديو إلى صورة (Nano Banana 2.1 و3.1‎ Flash و3.1‎ Flash Lite)

تتيح لك ميزة "تحويل الفيديو إلى صورة" إنشاء صور جديدة باستخدام سياق الفيديو كمرجع متعدد الوسائط. وهي مفيدة لإنشاء صور مصغّرة للفيديوهات عالية الجودة، أو ملصقات سينمائية، أو مخططات بيانية تلخيصية، أو أعمال فنية جديدة مستوحاة من مشهد فيديو.

أثناء عملية الإنشاء، يحلّل النموذج إطارات الفيديو في السياق لاستخراج المواضيع المرئية والأحداث الرئيسية، ثم يستخدمها مع طلبك النصي لإنشاء الصورة النهائية.

يمكنك تمرير عناوين URL العلنية على YouTube مباشرةً في طلب البيانات من واجهة برمجة التطبيقات أو تحميل ملفات الفيديو المحلية باستخدام 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<Content> 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");
            }
          }
        }
      }
    }
  }
}

Go

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 صورًا بدقة 1K تلقائيًا، ولكن يمكنها أيضًا إنشاء صور بدقة 2K و4K و512 بكسل (0.5K) (في Gemini 3.1 Flash Image فقط). لإنشاء مواد عرض بدقة أعلى، حدِّد image_size في response_format.

يجب استخدام حرف "K" كبير (مثلاً، 512 بكسل (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);
}

Go

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);
            }
          }
        }
      }
    }
  }
}

Go

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++;
            }
          }
        }
      }
    }
  }
}

Go

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 Image ‫minimal، high minimal
Gemini 3.1 Flash Lite Image ‫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);
}

Go

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، وهي مثالية إذا كنت بحاجة إلى إنشاء العديد من الصور.يمكنك الحصول على حدود أعلى لمعدّل الاستخدام مقابل وقت استجابة يصل إلى 24 ساعة.

الدليل الإرشادي لكتابة الطلبات والاستراتيجيات

يقدّم هذا القسم أمثلة على الطلبات ونماذج لمهام إنشاء الصور وتعديلها الشائعة. يتضمّن كل مثال نموذجًا قابلاً لإعادة الاستخدام وطلبًا نموذجيًا لـ Interactions API.

طلبات لإنشاء الصور

توضّح الأمثلة التالية كيفية استخدام الطلبات النصية لإنشاء أنواع مختلفة من الصور.

1. مشاهد واقعية

صِف مشهدًا بتفاصيل غنية. كلما كنت أكثر تحديدًا، زاد تحكمك في النتائج.

نموذج

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);
}

Go

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"
    }
  }'

2. رسومات توضيحية وملصقات منمّقة

صِف الأسلوب الفني والموضوع والوسيط. يُرجى تحديد التفاصيل المرئية (الخطوط العريضة والألوان وما إلى ذلك) للحصول على نتائج متّسقة.

نموذج

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);
            }
          }
        }
      }
    }
  }
}

Go

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."
  }'
ملصق بنمط &quot;كاواي&quot; لـ...
ملصق بنمط كاواي لباندا أحمر سعيد...

3- نص دقيق في الصور

يتميّز Gemini بقدرته على عرض النصوص. يجب أن يكون النص ونمط الخط (بشكل وصفي) والتصميم العام واضحًا. استخدام Gemini 3 Pro Image لإنشاء مواد عرض احترافية

نموذج

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);
            }
          }
        }
      }
    }
  }
}

Go

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"
    }
  }'
أريد إنشاء شعار حديث وبسيط لمقهى اسمه &quot;القهوة اليومية&quot;...
أريد إنشاء شعار عصري وبسيط لمقهى اسمه "القهوة اليومية"...

4. نماذج المنتجات والتصوير الفوتوغرافي التجاري

وهي مثالية لإنشاء لقطات منتجات واضحة واحترافية للتجارة الإلكترونية أو الإعلانات أو بناء الهوية البصرية للعلامة التجارية.

نموذج

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);
            }
          }
        }
      }
    }
  }
}

Go

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."
  }'
صورة عالية الدقة لمنتج تم التقاطها في استوديو بإضاءة جيدة، تعرض كوب قهوة من السيراميك بتصميم بسيط...
صورة عالية الدقة لمنتج في استوديو بإضاءة جيدة، تعرض كوب قهوة من السيراميك بتصميم بسيط...

5- تصاميم بسيطة ومساحة سلبية

هذا النمط ممتاز لإنشاء خلفيات للمواقع الإلكترونية أو العروض التقديمية أو المواد التسويقية التي سيتم وضع نص فوقها.

نموذج

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);
            }
          }
        }
      }
    }
  }
}

Go

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."
  }'
تصميم بسيط يعرض ورقة قيقب حمراء واحدة رقيقة...
صورة بسيطة تعرض ورقة قيقب حمراء واحدة رقيقة...

6. فن تسلسلي (لوحة قصص مصوّرة / لوحة ترتيب الصور)

تعتمد على الاتساق في مظهر الشخصية ووصف المشهد لإنشاء لوحات لسرد القصص المرئية. للحصول على دقة في النص وقدرة على سرد القصص، تعمل هذه الطلبات بشكل أفضل مع 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<Content> 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);
            }
          }
        }
      }
    }
  }
}

Go

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": "<BASE64_IMAGE_DATA>", "mime_type": "image/jpeg"}
    ]
  }'

الإدخال

الناتج

رجل يرتدي نظارة بيضاء
صورة الإدخال
أريد إنشاء قصة مصوّرة من 3 لوحات بأسلوب فني واقعي ومظلم...
أريد إنشاء قصة مصوّرة من 3 لوحات بأسلوب فني واقعي وقاتم...

استخدام "بحث 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);
            }
          }
        }
      }
    }
  }
}

Go

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"
    }
  }'
رسم بياني من إنشاء الذكاء الاصطناعي لنتيجة مباراة كرة قدم لفريق أرسنال
رسم بياني من إنشاء الذكاء الاصطناعي لنتيجة مباراة كرة قدم لفريق "أرسنال"

طلبات لتعديل الصور

توضّح هذه الأمثلة كيفية تقديم صور إلى جانب الطلبات النصية للتعديل والتركيب ونقل النمط.

1. إضافة العناصر وإزالتها

قدِّم صورة وصِف التغيير المطلوب. سيطابق النموذج نمط الصورة الأصلية وإضاءتها ومنظورها.

نموذج

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<Content> 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);
            }
          }
        }
      }
    }
  }
}

Go

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\": \"<BASE64_IMAGE_DATA>\"}
        ]
    }"

الإدخال

الناتج

صورة واقعية لقطة زنجبيلية منفوشة..
صورة واقعية لقطة برتقالية كثيفة الفرو...
باستخدام الصورة التي حمّلتُها لقطتي، أضِف قبعة ساحر صغيرة محبوكة...
باستخدام الصورة المرفقة لقطتي، أريد إضافة قبعة ساحر صغيرة محبوكة...

2. طلاء أجزاء من الصورة (إخفاء دلالي)

يمكنك تحديد "قناع" من خلال محادثة لتعديل جزء معيّن من الصورة بدون تغيير بقية الأجزاء.

نموذج

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<Content> 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);
            }
          }
        }
      }
    }
  }
}

Go

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\": \"<BASE64_IMAGE_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.\"}
      ]
    }"

الإدخال

الناتج

لقطة واسعة للشاشات الكبيرة عصرية ومضاءة جيدًا...
لقطة واسعة للشاشات الكبيرة حديثة ومضاءة جيدًا...
باستخدام الصورة المرفقة لغرفة معيشة، غيِّر فقط الأريكة الزرقاء إلى أريكة تشيسترفيلد كلاسيكية من الجلد البني...
باستخدام الصورة المقدَّمة لغرفة معيشة، أريد تغيير الأريكة الزرقاء فقط لتصبح أريكة تشيسترفيلد كلاسيكية من الجلد البني...

3- نقل النمط

يمكنك تقديم صورة والطلب من النموذج إعادة إنشاء محتواها بأسلوب فني مختلف.

نموذج

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<Content> 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);
            }
          }
        }
      }
    }
  }
}

Go

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\": \"<BASE64_IMAGE_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.\"}
      ]
    }"

الإدخال

الناتج

صورة واقعية عالية الدقة لشارع مزدحم في المدينة...
صورة واقعية عالية الدقة لشارع مزدحم في المدينة...
حوِّل الصورة المقدَّمة لشارع في مدينة حديثة ليلاً...
حوِّل الصورة المقدَّمة لشارع في مدينة حديثة ليلاً...

4. التركيب المتقدّم: دمج صور متعددة

يمكنك تقديم صور متعددة كسياق لإنشاء مشهد جديد مركّب. هذه الميزة مثالية لإنشاء نماذج تجريبية للمنتجات أو صور مجمّعة إبداعية.

نموذج

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<Content> 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);
            }
          }
        }
      }
    }
  }
}

Go

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\": \"<BASE64_IMAGE_DATA_1>\"},
            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},
            {\"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.\"}
      }]
    }"

المعلومة 1

المعلومة 2

الناتج

فستان صيفي أزرق مزيّن بنقشات زهور على خلفية محايدة
فستان صيفي أزرق مزيّن بالزهور على خلفية بلون محايد
لقطة كاملة لامرأة شعرها مربوط على شكل كعكة...
لقطة كاملة لامرأة شعرها مرفوع على شكل كعكة...
امرأة ترتدي فستانًا صيفيًا أزرق مزيّنًا بالزهور في مكان خارجي
امرأة ترتدي فستانًا صيفيًا أزرق مزيّنًا بالزهور في مكان خارجي

5- الحفاظ على التفاصيل بدقة عالية

لضمان الحفاظ على التفاصيل المهمة (مثل الوجه أو الشعار) أثناء التعديل، يُرجى وصفها بالتفصيل مع طلب التعديل.

نموذج

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<Content> 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);
            }
          }
        }
      }
    }
  }
}

Go

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\": \"<BASE64_IMAGE_DATA_1>\"},
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},
        {\"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.\"}
      ]
    }"

المعلومة 1

المعلومة 2

الناتج

صورة احترافية لوجه امرأة ذات شعر بني وعينين زرقاوين...
صورة شخصية احترافية لامرأة ذات شعر بني وعينين زرقاوين...
معرّف علامة تجارية حديث يتضمّن الحرفَين G وA
معرّف علامة تجارية حديث يتضمّن الحرفَين G وA
استخدِم الصورة الأولى للمرأة ذات الشعر البني والعينين الزرقاوين والتعبير المحايد...
استخدِم الصورة الأولى للمرأة ذات الشعر البني والعينين الزرقاوين والتعبير المحايد...

6. إضفاء الحيوية على شيء ما

حمِّل رسمًا تقريبيًا واطلب من النموذج تحسينه ليصبح صورة نهائية.

نموذج

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<Content> 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);
            }
          }
        }
      }
    }
  }
}

Go

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\": \"<BASE64_IMAGE_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.\"}
      ]
    }"

الإدخال

الناتج

رسم تخطيطي لسيارة
رسم تقريبي لسيارة
النتيجة التي تعرض السيارة النموذجية النهائية
صورة محسَّنة لسيارة

7. الاتساق في مظهر الشخصية: عرض بزاوية 360 درجة

يمكنك إنشاء مشاهد بزاوية 360 درجة لشخصية معيّنة من خلال طلب زوايا مختلفة بشكل متكرّر. للحصول على أفضل النتائج، يمكنك تضمين الصور التي تم إنشاؤها سابقًا في الطلبات اللاحقة للحفاظ على الاتساق. بالنسبة إلى الوضعيات المعقّدة، يجب تضمين صورة مرجعية للوضعية المحدّدة.

نموذج

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))

الإدخال

النتيجة 1

النتيجة 2

الصورة الأصلية لرجل يرتدي نظارات بيضاء
الصورة الأصلية
صورة لرجل يرتدي نظارة بيضاء وينظر إلى اليمين
رجل يرتدي نظارة بيضاء وينظر إلى اليمين
صورة لرجل يرتدي نظارة بيضاء وينظر إلى الأمام
رجل يرتدي نظارات بيضاء وينظر إلى الأمام

أفضل الممارسات

للارتقاء بنتائجك من جيدة إلى رائعة، يمكنك دمج هذه الاستراتيجيات الاحترافية في سير عملك.

  • قدِّموا تفاصيل دقيقة للغاية: كلما زادت التفاصيل، زاد تحكّمكم في النتيجة. بدلاً من "درع خيالي"، يمكنك وصفه كالتالي: "درع صفائحي مزخرف خاص بالجِن، منقوش بأوراق فضية، مع ياقة عالية ودرع كتف على شكل أجنحة صقر".
  • توفير السياق والغرض: اشرح الغرض من الصورة. سيؤثر فهم النموذج للسياق في النتيجة النهائية. على سبيل المثال، "أريد إنشاء شعار لعلامة تجارية راقية وبسيطة لمنتجات العناية بالبشرة" سيؤدي إلى نتائج أفضل من "أريد إنشاء شعار".
  • التكرار والتحسين: لا تتوقّع الحصول على صورة مثالية من المحاولة الأولى. استخدِم الطبيعة الحوارية للنموذج لإجراء تغييرات صغيرة. يمكنك المتابعة بطلبات مثل "هذا رائع، ولكن هل يمكنك جعل الإضاءة أكثر دفئًا؟" أو "أريد الحفاظ على كل شيء كما هو، ولكن أريد تغيير تعبيرات الشخصية لتكون أكثر جدية".
  • استخدام تعليمات مفصّلة: بالنسبة إلى المشاهد المعقّدة التي تحتوي على عناصر كثيرة، يمكنك تقسيم الطلب إلى خطوات. "أولاً، أنشئ خلفية لغابة هادئة وضبابية عند الفجر. بعد ذلك، أضِف في المقدّمة مذبحًا حجريًا قديمًا مغطّى بالطحالب. أخيرًا، ضع سيفًا واحدًا متوهجًا فوق المذبح".
  • استخدام "الطلبات السلبية الدلالية": بدلاً من قول "لا توجد سيارات"، يمكنك وصف المشهد المقصود بشكل إيجابي: "شارع فارغ ومهجور بدون أي علامات على حركة المرور".
  • التحكّم في الكاميرا: استخدِم لغة فوتوغرافية وسينمائية للتحكّم في التكوين. عبارات مثل wide-angle shot وmacro shot وlow-angle perspective

القيود

  • للحصول على أفضل أداء، استخدِم اللغات التالية: الإنجليزية والعربية (مصر) والألمانية (ألمانيا) والإسبانية (المكسيك) والفرنسية (فرنسا) والهندية (الهند) والإندونيسية (إندونيسيا) والإيطالية (إيطاليا) واليابانية (اليابان) والكورية (كوريا الجنوبية) والبرتغالية (البرازيل) والروسية (روسيا) والأوكرانية (أوكرانيا) والفيتنامية (فيتنام) والصينية (الصين).
  • لا يمكن استخدام الإدخالات الصوتية لإنشاء الصور. لا تتوفّر إمكانية إدخال الفيديوهات إلا في Gemini Nano Banana 2.1 وGemini 3.1 Flash Image وGemini 3.1 Flash Lite Image.
  • لن يلتزم النموذج دائمًا بالعدد الدقيق للصور التي يطلبها المستخدم صراحةً.
  • يعمل gemini-2.5-flash-image بشكل أفضل مع ما يصل إلى 3 صور كإدخال، بينما يدعم gemini-3-pro-image 5 صور بدقة عالية، وما يصل إلى 14 صورة في المجموع. يتيح gemini-nano-banana-2.1 وgemini-3.1-flash-image تشابه الشخصيات بما يصل إلى 4 شخصيات ودقة تصل إلى 10 عناصر في سير عمل واحد.
  • عند إنشاء نصّ من إنشاء الذكاء الاصطناعي لصورة، يعمل Gemini بشكل أفضل إذا أنشأت النص أولاً ثم طلبت صورة تتضمّن النص.
  • لا تتيح ميزة "التحقّق من المصادر باستخدام بحث Google" في gemini-nano-banana-2.1 وgemini-3.1-flash-image استخدام صور حقيقية لأشخاص من بحث الويب في الوقت الحالي.
  • تتضمّن جميع الصور التي يتم إنشاؤها علامة مائية من 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();

Go

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" }
    ]
  }'

نِسَب العرض إلى الارتفاع وحجم الصورة

بشكل تلقائي، يطابق النموذج حجم الصورة الناتجة مع حجم الصورة التي أدخلتها، أو ينشئ صورًا مربّعة بنسبة 1:1. يمكنك التحكّم في نسبة العرض إلى الارتفاع وحجم الصورة الناتجة باستخدام الحقلَين aspect_ratio وimage_size ضمن response_format عندما يتم ضبط type على "image".

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();

Go

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 ‫1,000 رمز مميّز دقة 2K ‫2,000 رمز مميّز درجة الدقة 4K ‫4 آلاف رمز مميّز
1:1 ‫1024×1024 1120 ‫2048×2048 1680 4096x4096 2520
1:4 ‫512×2048 1120 ‫1024x4096 1680 ‫2048×8192 2520
1:8 384x3072 1120 ‫768 × 6144 1680 ‫1536×12288 2520
2:3 848x1264 1120 ‫1696×2528 1680 ‫3392×5056 2520
3:2 ‎1264x848 1120 ‫2528×1696 1680 ‫5056×3392 2520
3:4 ‫896 × 1200 1120 ‫1792×2400 1680 ‫3584×4800 2520
4:1 ‫2048×512 1120 ‫4096×1024 1680 ‫8192×2048 2520
4:3 ‫1200 × 896 1120 ‫2400×1792 1680 ‫4800×3584 2520
4:5 928x1152 1120 ‫1856×2304 1680 ‫3712×4608 2520
5:4 ‫1152×928 1120 ‫2304×1856 1680 4608x3712 2520
8:1 3072x384 1120 ‫6144×768 1680 ‫12288×1536 2520
9:16 ‫768 × 1376 1120 ‫1536×2752 1680 ‫3072×5504 2520
‫16:9 ‫1376 × 768 1120 ‫2752x1536 1680 5504x3072 2520
21:9 ‫1584 × 672 1120 ‫3168×1344 1680 ‫6336×2688 2520

‫3.1‎ Flash Image

نسبة العرض إلى الارتفاع درجة الدقة 512 بكسل ‫0.5 ألف رمز مميّز دقة 1K ‫1,000 رمز مميّز دقة 2K ‫2,000 رمز مميّز درجة الدقة 4K ‫4 آلاف رمز مميّز
1:1 ‫512×512 747 ‫1024×1024 1120 ‫2048×2048 1680 4096x4096 2520
1:4 ‫256×1024 747 ‫512×2048 1120 ‫1024x4096 1680 ‫2048×8192 2520
1:8 ‫192 × 1536 747 384x3072 1120 ‫768 × 6144 1680 ‫1536×12288 2520
2:3 424x632 747 848x1264 1120 ‫1696×2528 1680 ‫3392×5056 2520
3:2 632 × 424 747 ‎1264x848 1120 ‫2528×1696 1680 ‫5056×3392 2520
3:4 ‫‎448 x 600 747 ‫896 × 1200 1120 ‫1792×2400 1680 ‫3584×4800 2520
4:1 ‫1024×256 747 ‫2048×512 1120 ‫4096×1024 1680 ‫8192×2048 2520
4:3 600 × 448 747 ‫1200 × 896 1120 ‫2400×1792 1680 ‫4800×3584 2520
4:5 ‫464×576 747 928x1152 1120 ‫1856×2304 1680 ‫3712×4608 2520
5:4 ‫576 × 464 747 ‫1152×928 1120 ‫2304×1856 1680 4608x3712 2520
8:1 1536x192 747 3072x384 1120 ‫6144×768 1680 ‫12288×1536 2520
9:16 ‫384 × 688 747 ‫768 × 1376 1120 ‫1536×2752 1680 ‫3072×5504 2520
‫16:9 688x384 747 ‫1376 × 768 1120 ‫2752x1536 1680 5504x3072 2520
21:9 ‫792×168 747 ‫1584 × 672 1120 ‫3168×1344 1680 ‫6336×2688 2520

‎3.1 Pro Image

نسبة العرض إلى الارتفاع دقة 1K ‫1,000 رمز مميّز دقة 2K ‫2,000 رمز مميّز درجة الدقة 4K ‫4 آلاف رمز مميّز
1:1 ‫1024×1024 1120 ‫2048×2048 1120 4096x4096 2000
2:3 848x1264 1120 ‫1696×2528 1120 ‫3392×5056 2000
3:2 ‎1264x848 1120 ‫2528×1696 1120 ‫5056×3392 2000
3:4 ‫896 × 1200 1120 ‫1792×2400 1120 ‫3584×4800 2000
4:3 ‫1200 × 896 1120 ‫2400×1792 1120 ‫4800×3584 2000
4:5 928x1152 1120 ‫1856×2304 1120 ‫3712×4608 2000
5:4 ‫1152×928 1120 ‫2304×1856 1120 4608x3712 2000
9:16 ‫768 × 1376 1120 ‫1536×2752 1120 ‫3072×5504 2000
‫16:9 ‫1376 × 768 1120 ‫2752x1536 1120 5504x3072 2000
21:9 ‫1584 × 672 1120 ‫3168×1344 1120 ‫6336×2688 2000

Gemini 2.5 Flash Image

نسبة العرض إلى الارتفاع الدقة الرموز المميزة
1:1 ‫1024×1024 1290
2:3 832x1248 1290
3:2 ‫1248×832 1290
3:4 ‫864×1184 1290
4:3 ‫1184×864 1290
4:5 896x1152 1290
5:4 ‫1152×896 1290
9:16 ‫768 × 1344 1290
16:9 ‫1344 × 768 1290
21:9 ‫1536 × 672 1290

حالات استخدام Imagen

تم إيقاف Imagen نهائيًا ولم يعُد متاحًا من خلال Gemini API. استخدام Nano Banana لإنشاء الصور وتعديلها

الخطوات التالية

  • يمكنك الاطّلاع على دليل Veo لمعرفة كيفية إنشاء فيديوهات باستخدام Gemini API.
  • لمزيد من المعلومات حول نماذج Gemini، يُرجى الاطّلاع على نماذج Gemini.