עריכת תמונות עם Gemini

‫Gemini תומך בעריכה משופרת של תמונות ובעריכה בכמה שלבים, וכולל מסנני בטיחות מעודכנים שמאפשרים חוויה גמישה יותר ופחות מגבילה.

אפשר לערוך תמונות במודלים הבאים של Gemini:

לחצו כדי להרחיב את רשימת המודלים הנתמכים

מידע נוסף על יכולות המודלים זמין במאמר מודלים של Gemini.

איך עורכים תמונה

המסוף

כדי לערוך תמונות:

  1. פותחים את Agent Studio > יצירת הנחיה.
  2. לוחצים על החלפת מודל ובוחרים אחד מהמודלים שמוצגים.
  3. בחלונית Outputs, בוחרים באפשרות Image and text בתפריט הנפתח.
  4. לוחצים על הוספת מדיה (), בוחרים מקור מהתפריט ופועלים לפי ההוראות בתיבת הדו-שיח.
  5. כותבים את השינויים שרוצים לבצע בתמונה בכתיבת הנחיה אזור הטקסט.
  6. לוחצים על הכפתור הנחיה ().

‫Gemini יוצר גרסה ערוכה של התמונה שסיפקתם על סמך התיאור שלכם. התהליך הזה נמשך כמה שניות, אבל יכול להיות איטי יותר בהתאם לקיבולת.

Python

התקנה

pip install --upgrade google-genai

מידע נוסף זמין במאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import GenerateContentConfig, Modality
from PIL import Image
from io import BytesIO

client = genai.Client()

# Using an image of Eiffel tower, with fireworks in the background.
image = Image.open("test_resources/example-image-eiffel-tower.png")

response = client.models.generate_content(
    model="gemini-3.1-flash-image",
    contents=[image, "Edit this image to make it look like a cartoon."],
    config=GenerateContentConfig(response_modalities=[Modality.TEXT, Modality.IMAGE]),
)
for part in response.candidates[0].content.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        image = Image.open(BytesIO((part.inline_data.data)))
        image.save("output_folder/bw-example-image.png")

Java

איך מתקינים או מעדכנים את Java

מידע נוסף זמין במאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.Candidate;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashEditImageWithTextAndImage {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash-image";
    String outputFile = "resources/output/bw-example-image.png";
    generateContent(modelId, outputFile);
  }

  // Edits an image with image and text input
  public static void generateContent(String modelId, String outputFile) throws IOException {
    // Client Initialization. Once created, it can be reused for multiple requests.
    try (Client client = Client.builder().location("global").vertexAI(true).build()) {

      byte[] localImageBytes =
          Files.readAllBytes(Paths.get("resources/example-image-eiffel-tower.png"));

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromBytes(localImageBytes, "image/png"),
                  Part.fromText("Edit this image to make it look like a cartoon.")),
              GenerateContentConfig.builder().responseModalities("TEXT", "IMAGE").build());

      // Get parts of the response
      List<Part> parts =
          response
              .candidates()
              .flatMap(candidates -> candidates.stream().findFirst())
              .flatMap(Candidate::content)
              .flatMap(Content::parts)
              .orElse(new ArrayList<>());

      // For each part print text if present, otherwise read image data if present and
      // write it to the output file
      for (Part part : parts) {
        if (part.text().isPresent()) {
          System.out.println(part.text().get());
        } else if (part.inlineData().flatMap(Blob::data).isPresent()) {
          BufferedImage image =
              ImageIO.read(new ByteArrayInputStream(part.inlineData().flatMap(Blob::data).get()));
          ImageIO.write(image, "png", new File(outputFile));
        }
      }

      System.out.println("Content written to: " + outputFile);

      // Example response:
      // No problem! Here's the image in a cartoon style...
      //
      // Content written to: resources/output/bw-example-image.png
    }
  }
}

Go

איך מתקינים או מעדכנים את Go

מידע נוסף זמין במאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"fmt"
	"io"
	"os"

	"google.golang.org/genai"
)

// generateImageMMFlashEditWithTextImg demonstrates editing an image with text and image inputs.
func generateImageMMFlashEditWithTextImg(w io.Writer) error {
	// TODO(developer): Update below lines
	outputFile := "bw-example-image.png"
	inputFile := "example-image-eiffel-tower.png"
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	image, err := os.ReadFile(inputFile)
	if err != nil {
		return fmt.Errorf("failed to read image: %w", err)
	}

	modelName := "gemini-2.5-flash-image"
	prompt := "Edit this image to make it look like a cartoon."
	contents := []*genai.Content{
		{
			Role: "user",
			Parts: []*genai.Part{
				{Text: prompt},
				{InlineData: &genai.Blob{
					MIMEType: "image/png",
					Data:     image,
				}},
			},
		},
	}
	resp, err := client.Models.GenerateContent(ctx,
		modelName,
		contents,
		&genai.GenerateContentConfig{
			ResponseModalities: []string{
				string(genai.ModalityText),
				string(genai.ModalityImage),
			},
		},
	)
	if err != nil {
		return fmt.Errorf("failed to generate content: %w", err)
	}

	if len(resp.Candidates) == 0 || resp.Candidates[0].Content == nil {
		return fmt.Errorf("no content was generated")
	}

	for _, part := range resp.Candidates[0].Content.Parts {
		if part.Text != "" {
			fmt.Fprintln(w, part.Text)
		} else if part.InlineData != nil {
			if len(part.InlineData.Data) > 0 {
				if err := os.WriteFile(outputFile, part.InlineData.Data, 0644); err != nil {
					return fmt.Errorf("failed to save image: %w", err)
				}
				fmt.Fprintln(w, outputFile)
			}
		}
	}

	// Example response:
	// Here's the image of the Eiffel Tower and fireworks, cartoonized for you!
	// Cartoon-style edit:
	//  - Simplified the Eiffel Tower with bolder lines and slightly exaggerated proportions.
	//  - Brightened and saturated the colors of the sky, fireworks, and foliage for a more vibrant, cartoonish look.
	//  ....
	return nil
}

Node.js

התקנה

npm install @google/genai

מידע נוסף זמין במאמרי העזרה של ה-SDK.

מגדירים משתני סביבה כדי להשתמש ב-Google Gen AI SDK עם Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_ENTERPRISE=True

const fs = require('fs');
const {GoogleGenAI, Modality} = require('@google/genai');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION =
  process.env.GOOGLE_CLOUD_LOCATION || 'us-central1';

const FILE_NAME = 'test-data/example-image-eiffel-tower.png';

async function generateImage(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const imageBytes = fs.readFileSync(FILE_NAME);

  const response = await client.models.generateContent({
    model: 'gemini-2.5-flash-image',
    contents: [
      {
        role: 'user',
        parts: [
          {
            inlineData: {
              mimeType: 'image/png',
              data: imageBytes.toString('base64'),
            },
          },
          {
            text: 'Edit this image to make it look like a cartoon',
          },
        ],
      },
    ],
    config: {
      responseModalities: [Modality.TEXT, Modality.IMAGE],
    },
  });

  for (const part of response.candidates[0].content.parts) {
    if (part.text) {
      console.log(`${part.text}`);
    } else if (part.inlineData) {
      const outputDir = 'output-folder';
      if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, {recursive: true});
      }
      const imageBytes = Buffer.from(part.inlineData.data, 'base64');
      const filename = `${outputDir}/bw-example-image.png`;
      fs.writeFileSync(filename, imageBytes);
    }
  }

  // Example response:
  // Okay, I will edit this image to give it a cartoonish style, with bolder outlines, simplified details, and more vibrant colors.
  return response;
}

REST

כדי ליצור או להחליף את הקובץ הזה בספרייה הנוכחית, מריצים את הפקודה הבאה בטרמינל:

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${API_ENDPOINT}:generateContent \
  -d '{
    "contents": {
      "role": "USER",
      "parts": [
        {"fileData": {
          "mimeType": "image/jpg",
          "fileUri": "FILE_NAME"
          }
        },
        {"text": "Convert this photo to black and white, in a cartoonish style."},
      ]

    },
    "generationConfig": {
      "imageConfig": {
        "aspectRatio": "16:9",
        "imageSize": "4K",
        "responseModalities": ["TEXT", "IMAGE"],
        "imageOutputOptions": {
          "mimeType": "image/png"
        },
      "personGeneration": "allow_all"
      },
    },
    "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

מידע נוסף על יכולות המודל, כולל יחסי גובה-רוחב ורזולוציות פלט נתמכים, זמין במאמר מודלים של Gemini.

‫Gemini יוצר תמונה על סמך התיאור שלכם. התהליך הזה נמשך כמה שניות, אבל יכול להיות איטי יותר בהתאם לקיבולת.

שמירת התמונות הערוכות ב-Cloud Storage

כשעורכים תמונות באמצעות מודלים של Gemini ליצירת תמונות, כמו Gemini Nano Banana 2.1 (gemini-nano-banana-2.1), באמצעות ממשקי ה-API של generateContent ו-streamGenerateContent, אפשר להגדיר את outputConfig.outputUriPrefix ו-generationConfig.responseFormat[].image.delivery ל-"URI" כדי לכתוב תמונות ערוכות ישירות לקטגוריה של Cloud Storage ולקבל הפניה של fileData.fileUri במקום בייטים של base64 בתוך השורה. במאמר שמירת תמונות שנוצרו על ידי AI ב-Cloud Storage מפורטים המודלים הנתמכים, הוראות ההגדרה ותחביר הבקשה.

עריכת תמונות בכמה שלבים

עריכה בכמה שלבים מאפשרת לכם להגיב למודל עם שינויים אחרי שהוא מציג תשובה עם תמונה ערוכה.

המודלים הבאים של Gemini תומכים בעריכה בכמה שלבים:

לחצו כדי להרחיב את רשימת המודלים הנתמכים

כל קובץ מצורף מוטבע לא יכול לחרוג מ-256MB, והמטען הייעודי (payload) הכולל של הבקשה הדחוסה לא יכול לחרוג מ-500MiB.

כדי לבדוק את עריכת התמונות בכמה שלבים, אפשר לעיין ב-notebook‏ Gemini Nano Banana 2.1 Image Generation in Agent Platform.

במאמר דוגמה לעריכת תמונות בכמה שלבים באמצעות חתימות מחשבה יש דוגמאות קוד שקשורות ליצירה ולעריכה של תמונות בכמה שלבים באמצעות Gemini 3 Pro Image.

המאמרים הבאים

בקישורים הבאים מופיע מידע נוסף על יצירת תמונות באמצעות Gemini: