使用 Gemini 生成圖片

Gemini 2.5 Flash 圖片預覽功能支援生成多種模態的回覆,包括文字和圖片。

圖像生成

Gemini Flash 搶先版圖像生成功能公開預先發布 (gemini-2.5-flash-image-preview) 除了文字,也支援生成圖像。這項功能可擴充 Gemini 的能力,包括:

  • 透過自然語言對話反覆生成圖像,並在調整圖像時維持一致性和背景資訊。
  • 生成圖片,並以高品質算繪長文字。
  • 生成文字和圖片夾雜的內容。舉例來說,單一回合的網誌文章包含文字和圖片。先前,這需要將多個模型串連在一起。
  • 運用 Gemini 的世界知識和推論能力生成圖片。

這個公開實驗版可生成 1024 像素的圖片、支援生成人物圖像,並提供更新的安全篩選器,讓使用者體驗更靈活、限制更少。

支援的模式和功能如下:

  • 文字轉圖像

    • 範例提示:「生成一張艾菲爾鐵塔的圖片,背景要有煙火。」
  • 文字轉圖像 (文字算繪)

    • 提示範例:「生成一張電影風格的照片,照片中有一棟大型建築,建築正面投射出巨型文字:「Gemini 2.5 現在可以生成長篇文字」」
  • 文字轉圖像和文字 (交錯)

    • 範例提示:「Generate an illustrated recipe for a paella. 在生成食譜的同時建立圖像。」
    • 提示範例:「生成以 3D 卡通動畫風格呈現的小狗故事。為每個場景生成圖片
  • 圖片和文字轉換為圖片和文字 (交錯)

    • 範例提示詞: (附上已擺放家具的房間圖片)「我的空間適合擺放哪些其他顏色的沙發?可以更新圖片嗎?
  • 支援地區語言的圖像生成功能

    • 範例提示:「生成早餐圖片。」

限制:

  • 為獲得最佳成效,請使用下列語言:英文、西班牙文 (墨西哥)、日文、中文 (中國)、印地文。
  • 圖像生成功能不支援音訊或影片輸入內容。
  • 系統不一定會觸發圖像生成功能:
    • 模型可能只會輸出文字。請明確要求生成圖像。例如「請在過程中提供圖片」。
    • 模型可能會以圖片形式生成文字,請明確要求文字輸出內容。例如「生成敘事文字和插圖」。
    • 模型可能會中途停止生成內容。請再試一次或改用其他提示。

生成圖像

以下章節說明如何使用 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. 在「撰寫提示」文字區域中,輸入要生成的圖片說明。舉例來說,「製作教學課程,說明如何用簡單三步驟製作花生醬和果醬三明治。針對每個步驟,提供標題 (附上步驟編號)、說明,並生成圖片,每張圖片的長寬比為 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. 在「撰寫提示」文字區域中,輸入要生成的圖片說明。例如:「Generate a photo of a typical breakfast.」(生成一張典型早餐的相片。)
  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 會根據你的描述生成圖片。這項程序應該只需要幾秒鐘,但視容量而定,速度可能會較慢。