Gemini で画像を編集する

Gemini 2.5 Flash Image は、複数のタイプの画像編集をサポートしています。

画像編集

画像生成(gemini-2.5-flash-image)の Gemini 2.5 Flash Image では、画像の生成のほか編集もサポートされています。Gemini 2.5 Flash Image では、画像の編集とマルチターン編集が改善され、より柔軟で制限の少ないユーザー エクスペリエンスを提供するように更新された安全フィルタが含まれています。

次のモダリティと機能がサポートされています。

  • 画像編集(テキストと画像による画像変換)

    • プロンプトの例: 「この画像を編集してカートゥーンのようにして」
    • プロンプトの例: [猫の画像] + [枕の画像] + 「この枕に猫のクロスステッチを作成してください」。
  • マルチターン画像編集(チャット)

    • プロンプトの例: [青い車の画像をアップロードして] 「この車をコンバーチブルにして。」「今度は色を黄色に変えて。」「スポイラーを追加して。」

画像を編集する

コンソール

画像を編集するには:

  1. [Vertex AI Studio] > [プロンプトを作成] を開きます。
  2. [モデルの切り替え] をクリックし、メニューから gemini-2.5-flash-image を選択します。
  3. [出力] パネルで、プルダウン メニューから [画像とテキスト] を選択します。
  4. [メディアを挿入]()をクリックし、メニューからソースを選択して、ダイアログの指示に沿って操作します。
  5. [プロンプトを入力] テキスト領域に、画像に加える編集内容を入力します。
  6. [プロンプト]()ボタンをクリックします。

Gemini は、入力された説明に基づいて、提供された画像の編集バージョンを生成します。このプロセスには数秒かかりますが、容量によっては比較的遅くなることがあります。

Python

インストール

pip install --upgrade google-genai

詳しくは、SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# 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_VERTEXAI=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-2.5-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")
# Example response:
#  Here's the cartoon-style edit of the image:
#  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.
#  ....

Java

Java をインストールまたは更新します。

詳しくは、SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# 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_VERTEXAI=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
    }
  }
}

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": [
        {"file_data": {
          "mime_type": "image/jpg",
          "file_uri": "<var>FILE_NAME</var>"
          }
        },
        {"text": "Convert this photo to black and white, in a cartoonish style."},
      ]

    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
      "image_config": {
        "aspect_ratio": "16:9",
      },
    },
    "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini は、説明に基づいて画像を生成します。このプロセスには数秒かかりますが、容量によっては比較的遅くなることがあります。

マルチターンの画像編集

Gemini 2.5 Flash Image では、マルチターン編集の改善もサポートされています。これにより、編集された画像レスポンスを受け取った後に、変更内容をモデルに送信できます。これにより、画像を会話によって編集し続けることができます。

リクエスト ファイル全体のサイズは、最大 50 MB に制限することをおすすめします。

マルチターンの画像編集を試すには、Gemini 2.5 Flash Image ノートブックをお試しください。