Gemini で画像を生成する

Gemini 2.5 Flash Image Preview では、テキストや画像など、複数のモダリティでのレスポンス生成がサポートされています。

画像生成

画像生成の Gemini Flash プレビュー版(gemini-2.5-flash-image-preview)では、テキストに加えて画像を生成する機能がサポートされています。これにより、Gemini の機能が次のように拡張されます。

  • 自然言語による会話を通じて画像を繰り返し生成し、一貫性とコンテキストを維持しながら画像を調整します。
  • 高品質の長いテキスト レンダリングで画像を生成します。
  • インターリーブされたテキストと画像の出力を生成します。たとえば、1 つのターンにテキストと画像を含むブログ投稿などです。以前は、これを行うには複数のモデルを連携させる必要がありました。
  • Gemini の世界の知識と推論機能を使用して画像を生成します。

この公開試験運用版では、Gemini 2.5 Flash Image Preview で 1,024 ピクセルの画像を生成できます。また、人物の画像生成に対応し、より柔軟で制限の少ないユーザー エクスペリエンスを提供するよう更新された安全フィルターが含まれています。

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

  • テキストから画像

    • プロンプトの例: 「背景に花火があるエッフェル塔の画像を生成してください」。
  • テキストから画像(テキスト レンダリング)

    • プロンプトの例: 「この巨大なテキスト投影が建物の正面にマッピングされた大きな建物の映画のような写真を生成してください。「Gemini 2.5 で長文のテキストを生成できるようになりました」」
  • テキスト画像変換とテキスト(インターリーブ)

    • プロンプトの例: 「パエリアのレシピをイラスト付きで生成してください。レシピの生成時に、テキストと一緒に表示する画像を作成します」。
    • プロンプトの例: 「3D アニメーション スタイルの犬の物語を生成して。各シーンの画像を生成して」
  • 画像とテキスト画像変換とテキスト(インターリーブ)

    • プロンプトの例:(家具付きの部屋の画像を提示して)「この部屋に合いそうなソファの色には他にどんなものがありますか?画像を更新できますか?」
  • 言語 / 地域に対応した画像生成

    • プロンプトの例: 「朝食の画像を生成してください。」

制限事項:

  • 最高のパフォーマンスを実現するには、EN、es-MX、ja-JP、zh-CN、hi-IN のいずれかの言語を使用してください。
  • 画像生成では、音声や動画の入力はサポートされていません。
  • 画像生成がトリガーされない場合があります。
    • モデルがテキストのみを出力する場合があります。画像出力を明示的に指示してみてください。例: 「作業時に画像を提供してください。」
    • モデルがテキストを画像として生成する場合があります。テキスト出力を明示的にリクエストしてみてください。たとえば、「イラストとともに物語のテキストを生成して」などです。
    • モデルの生成が途中で停止することがあります。もう一度お試しいただくか、別のプロンプトをお試しください。

画像を生成

以降のセクションでは、Vertex AI Studio または API を使用して画像を生成する方法について説明します。

プロンプトのガイダンスとベスト プラクティスについては、マルチモーダル プロンプトを設計するをご覧ください。

コンソール

画像生成を使用するには:

  1. [Vertex AI Studio] > [プロンプトを作成] を開きます。
  2. [モデルを切り替える] をクリックし、メニューから gemini-2.5-flash-image-preview を選択します。
  3. [出力] パネルで、プルダウン メニューから [画像とテキスト] を選択します。
  4. [プロンプトを入力] テキスト領域に、生成する画像の説明を入力します。
  5. [プロンプト]()ボタンをクリックします。

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

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=("Generate an image of the Eiffel tower with fireworks in the background."),
    config=GenerateContentConfig(
        response_modalities=[Modality.TEXT, Modality.IMAGE],
        candidate_count=1,
        safety_settings=[
            {"method": "PROBABILITY"},
            {"category": "HARM_CATEGORY_DANGEROUS_CONTENT"},
            {"threshold": "BLOCK_MEDIUM_AND_ABOVE"},
        ],
    ),
)
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/example-image-eiffel-tower.png")
# Example response:
#   I will generate an image of the Eiffel Tower at night, with a vibrant display of
#   colorful fireworks exploding in the dark sky behind it. The tower will be
#   illuminated, standing tall as the focal point of the scene, with the bursts of
#   light from the fireworks creating a festive atmosphere.

Node.js

インストール

npm install @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

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';

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

  const response = await ai.models.generateContentStream({
    model: 'gemini-2.0-flash-exp',
    contents:
      'Generate an image of the Eiffel tower with fireworks in the background.',
    config: {
      responseModalities: [Modality.TEXT, Modality.IMAGE],
    },
  });

  const generatedFileNames = [];
  let imageIndex = 0;
  for await (const chunk of response) {
    const text = chunk.text;
    const data = chunk.data;
    if (text) {
      console.debug(text);
    } else if (data) {
      const fileName = `generate_content_streaming_image_${imageIndex++}.png`;
      console.debug(`Writing response image to file: ${fileName}.`);
      try {
        fs.writeFileSync(fileName, data);
        generatedFileNames.push(fileName);
      } catch (error) {
        console.error(`Failed to write image file ${fileName}:`, error);
      }
    }
  }

  return generatedFileNames;
}

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": { "text": "Create a tutorial explaining how to make a peanut butter and jelly sandwich in three easy steps."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
     },
     "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini は、入力された説明に基づいて画像を生成します。この処理には数秒かかりますが、容量によっては比較的遅くなることがあります。

画像とテキストが混在するコンテンツを生成する

Gemini 2.5 Flash Image Preview は、テキスト レスポンスと画像を交互に生成できます。たとえば、生成されたレシピの各ステップがどのようなものになるかを示す画像を、そのステップのテキストに合わせて生成できます。そのため、モデルに個別のリクエストを送信する必要はありません。

コンソール

テキスト レスポンスと画像が混在するコンテンツを生成するには:

  1. [Vertex AI Studio] > [プロンプトを作成] を開きます。
  2. [モデルを切り替える] をクリックし、メニューから gemini-2.5-flash-image-preview を選択します。
  3. [出力] パネルで、プルダウン メニューから [画像とテキスト] を選択します。
  4. [プロンプトを入力] テキスト領域に、生成する画像の説明を入力します。たとえば、「ピーナッツ バターとジャムのサンドイッチを 3 つの簡単なステップで作る方法を説明するチュートリアルを作成して。各ステップについて、ステップの番号と説明を含むタイトルを付け、画像も生成してください。各画像の縦横比は 1:1 で生成してください。」
  5. [プロンプト]()ボタンをクリックします。

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

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=(
        "Generate an illustrated recipe for a paella."
        "Create images to go alongside the text as you generate the recipe"
    ),
    config=GenerateContentConfig(response_modalities=[Modality.TEXT, Modality.IMAGE]),
)
with open("output_folder/paella-recipe.md", "w") as fp:
    for i, part in enumerate(response.candidates[0].content.parts):
        if part.text is not None:
            fp.write(part.text)
        elif part.inline_data is not None:
            image = Image.open(BytesIO((part.inline_data.data)))
            image.save(f"output_folder/example-image-{i+1}.png")
            fp.write(f"![image](example-image-{i+1}.png)")
# Example response:
#  A markdown page for a Paella recipe(`paella-recipe.md`) has been generated.
#   It includes detailed steps and several images illustrating the cooking process.

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": { "text": "Create a tutorial explaining how to make a peanut butter and jelly sandwich in three easy steps. For each step, provide a title with the number of the step, an explanation, and also generate an image, generate each image in a 1:1 aspect ratio."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
     },
     "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini は、入力された説明に基づいて画像を生成します。この処理には数秒かかりますが、容量によっては比較的遅くなることがあります。

言語 / 地域に対応した画像生成

Gemini 2.5 Flash 画像プレビューでは、テキストや画像の回答を提供する際に、位置情報を含めることもできます。たとえば、モデルに場所を指定しなくても、現在の場所を考慮した場所や体験の画像を生成できます。

コンソール

言語 / 地域に対応した画像生成を使用するには:

  1. [Vertex AI Studio] > [プロンプトを作成] を開きます。
  2. [モデルを切り替える] をクリックし、メニューから gemini-2.5-flash-image-preview を選択します。
  3. [出力] パネルで、プルダウン メニューから [画像とテキスト] を選択します。
  4. [プロンプトを入力] テキスト領域に、生成する画像の説明を入力します。たとえば、「典型的な朝食の写真を生成して」などです。
  5. [プロンプト]()ボタンをクリックします。

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

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=("Generate a photo of a breakfast meal."),
    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/example-breakfast-meal.png")
# Example response:
#   Generates a photo of a vibrant and appetizing breakfast meal.
#   The scene will feature a white plate with golden-brown pancakes
#   stacked neatly, drizzled with rich maple syrup and ...

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": { "text": "Generate a photo of a typical breakfast."},
    },
    "generation_config": {
      "response_modalities": ["TEXT", "IMAGE"],
     },
     "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

Gemini は、入力された説明に基づいて画像を生成します。この処理には数秒かかりますが、容量によっては比較的遅くなることがあります。