使用 Gemini 生成和修改图片

以下 Gemini 模型支持生成图片和文本的功能:

  • Gemini 2.5 Flash Image,也称为 Gemini 2.5 Flash(使用 Nano Banana)

  • Gemini 3 Pro Image(预览版),也称为 Gemini 3 Pro(使用 Nano Banana)

这可扩展 Gemini 的功能,使其能够执行以下操作:

  • 通过自然语言对话迭代生成图片,在调整图片的同时保持一致性和上下文。
  • 生成具有高质量长文本渲染效果的图片。
  • 生成图文交织的输出。例如,在单个对话轮次中包含文本和图片的博文。以前,这需要将多个模型串联在一起。
  • 利用 Gemini 的世界知识和推理能力生成图片。

Gemini 2.5 Flash Image (gemini-2.5-flash-image) 和 Gemini 3 Pro Image 预览版 (gemini-3-pro-image-preview) 支持生成人物图片,并包含更新的安全过滤条件,可提供更灵活、限制更少的用户体验。Gemini 2.5 Flash Image 可以生成 1,024 像素的图片。Gemini 3 Pro Image 可以生成最大 4096 像素的图片。

这两款模型都支持以下模态和功能:

  • 文本到图像

    • 提示示例:“生成一张以烟花为背景的埃菲尔铁塔图片。”
  • 文生图(文本渲染)

    • 提示示例:“生成一张电影效果照片,照片中有一栋大型建筑,建筑正面投影着巨大的文字:‘Gemini 3 现在可以生成长篇文本了’”
  • 文生图和文本(交织)

    • 提示示例:“生成一份图文并茂的海鲜饭食谱。在生成食谱时,与文本一起创建图片。”
    • 提示示例:“生成一个关于狗狗的故事,采用 3D 卡通动画风格。为每个场景生成一张图片”
  • 图片和文生图及文本(交织)

    • 提示示例:(附带一张带家具的房间的照片)“我的空间还适合放置哪些颜色的沙发?您可以更新图片吗?”

最佳实践

如需改善图片生成效果,请遵循以下最佳实践:

  • 具体化:提供更多细节,以便您更好地掌控输出结果。例如,与其使用“奇幻盔甲”,不如尝试“华丽的精灵板甲,蚀刻着银叶图案,带有高领和猎鹰翅膀形状的肩甲”。

  • 提供上下文和意图:说明图片的用途,帮助模型理解上下文。例如,“为高端极简护肤品牌设计徽标”的效果要好于“设计徽标”。

  • 迭代和优化:不要指望第一次尝试就能生成完美的图片。使用后续提示进行小幅更改,例如“让光线更暖一些”或“让角色的表情更严肃一些”。

  • 使用分步指令:对于复杂场景,将您的请求拆分为多个步骤。例如,“首先,创建一个宁静、薄雾弥漫的黎明森林的背景。然后,在前景中添加一个长满苔藓的古老石制祭坛。最后,将一把发光的剑放在祭坛顶部。”

  • 描述您想要的内容,而不是不想要的内容:不要说“没有汽车”,而是通过说“一条没有交通迹象的空旷、荒凉的街道”来正面描述场景。

  • 控制镜头:引导镜头视图。使用摄影和电影术语来描述构图,例如“广角镜头”“微距镜头”或“低角度视角”。

  • 图片提示:使用“创建一张…的图片”或“生成一张…的图片”之类的短语来描述意图。否则,多模态模型可能会以文本而非图片的形式做出回答。

  • 传递思维签名: 使用 Gemini 3 Pro Image 时,我们建议您在多轮图片创建和修改期间将思维签名传递回模型。这样一来,您就可以在多次互动中保留推理上下文。如需查看与使用 Gemini 3 Pro Image 进行多轮图片修改相关的代码示例,请参阅使用思维签名的多轮图片修改示例

限制:

  • 为了获得 Gemini 2.5 Flash Image 的最佳性能,请使用以下语言:EN、es-MX、ja-JP、zh-CN 或 hi-IN。为了获得 Gemini 3 Pro Image 的最佳性能,请使用以下语言:ar-EG、de-DE、EN、es-MX、fr-FR、hi-IN、id-ID、it-IT、ja-JP、ko-KR、pt-BR、ru-RU、ua-UA、vi-VN 和 zh-CN

  • 图片生成不支持音频或视频输入。

  • 模型可能不会生成您要求的确切数量的图片。

  • 为获得最佳效果,请在使用 Gemini 2.5 Flash Image 时在输入中最多添加 3 张图片。为获得最佳效果,请在使用 Gemini 3 Pro Image 时在输入中最多添加 14 张图片。

  • 生成包含文本的图片时,请先生成文本,然后再生成包含该文本的图片。

  • 在以下情况下,图片或文本生成功能可能无法按预期工作:

    • 如果提示不明确,模型可能只会生成文本,而不会生成图片。如果您想要图片,请在请求中明确要求生成图片。例如,“在您操作过程中提供图片”。

    • 模型可能会以图片形式生成文本。如要生成文本,请明确要求输出文本。例如,“生成叙事文本及插图”。

    • 即使模型尚未完成生成,也可能会停止生成内容。如果出现这种情况,请重试或使用其他提示。

    • 如果提示可能不安全,模型可能不会处理相应请求,并会返回一条表明无法生成不安全图片的回答。在这种情况下,FinishReasonSTOP

生成图片

以下部分介绍了如何使用 Vertex AI Studio 或 API 生成图片。

如需了解提示方面的指南和最佳实践,请参阅设计多模态提示

控制台

如需使用图片生成,请执行以下操作:

  1. 依次打开 Vertex AI Studio > 创建提示
  2. 点击切换模型,然后从菜单中选择以下模型之一:
    • gemini-2.5-flash-image
    • gemini-3-pro-image-preview
  3. 输出面板中,从下拉菜单中选择图片和文本
  4. 编写提示文本区域中,撰写要生成的图片的说明。
  5. 点击提示 () 按钮。

Gemini 将根据您的说明生成图片。此过程需要几秒钟,但可能会相对较慢,具体取决于容量。

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 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_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-3-pro-image-preview",
    contents=("Generate an image of the Eiffel tower with fireworks in the background."),
    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-image-eiffel-tower.png")

Node.js

安装

npm install @google/genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 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_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 generateImage(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
  });

  const response = await client.models.generateContentStream({
    model: 'gemini-2.5-flash-image',
    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 outputDir = 'output-folder';
      if (!fs.existsSync(outputDir)) {
        fs.mkdirSync(outputDir, {recursive: true});
      }
      const fileName = `${outputDir}/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);
      }
    }
  }

  // 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.

  return generatedFileNames;
}

Java

了解如何安装或更新 Java

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 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_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 com.google.genai.types.SafetySetting;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashWithText {

  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/example-image-eiffel-tower.png";
    generateContent(modelId, outputFile);
  }

  // Generates an image with 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()) {

      GenerateContentConfig contentConfig =
          GenerateContentConfig.builder()
              .responseModalities("TEXT", "IMAGE")
              .candidateCount(1)
              .safetySettings(
                  SafetySetting.builder()
                      .method("PROBABILITY")
                      .category("HARM_CATEGORY_DANGEROUS_CONTENT")
                      .threshold("BLOCK_MEDIUM_AND_ABOVE")
                      .build())
              .build();

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              "Generate an image of the Eiffel tower with fireworks in the background.",
              contentConfig);

      // 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:
      // Here is the Eiffel Tower with fireworks in the background...
      //
      // Content written to: resources/output/example-image-eiffel-tower.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": [
        {
          "text": "Create a tutorial explaining how to make a peanut butter and jelly sandwich in three easy steps."
        }
      ]
    },
    "generationConfig": {
      "responseModalities": ["TEXT", "IMAGE"],
      "imageConfig": {
        "aspectRatio": "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 可以生成图文交织的回答。例如,您可以生成所生成食谱中每个步骤的图片,以便与该步骤的文本搭配使用,而无需单独向模型发出请求。

控制台

如需生成图文交织的回答,请执行以下操作:

  1. 依次打开 Vertex AI Studio > 创建提示
  2. 点击切换模型,然后从菜单中选择以下模型之一:
    • gemini-2.5-flash-image
    • gemini-3-pro-image-preview
  3. 输出面板中,从下拉菜单中选择图片和文本
  4. 编写提示文本区域中,撰写要生成的图片的说明。例如,“创建一个教程,说明如何通过三个简单步骤制作花生酱和果酱三明治。对于每个步骤,提供一个包含步骤编号的标题、一段说明,并生成一张图片,每张图片的宽高比为 1:1。”
  5. 点击提示 () 按钮。

Gemini 将根据您的说明生成回答。此过程需要几秒钟,但可能会相对较慢,具体取决于容量。

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 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_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-3-pro-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)")

Java

了解如何安装或更新 Java

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 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_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.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

public class ImageGenMmFlashTextAndImageWithText {

  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/paella-recipe.md";
    generateContent(modelId, outputFile);
  }

  // Generates text and image with 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()) {

      GenerateContentResponse response =
          client.models.generateContent(
              modelId,
              Content.fromParts(
                  Part.fromText("Generate an illustrated recipe for a paella."),
                  Part.fromText(
                      "Create images to go alongside the text as you generate the recipe.")),
              GenerateContentConfig.builder().responseModalities("TEXT", "IMAGE").build());

      try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

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

        int index = 1;
        // 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()) {
            writer.write(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("resources/output/example-image-" + index + ".png"));
            writer.write("![image](example-image-" + index + ".png)");
          }
          index++;
        }

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

        // 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.
        //
        // Content written to:  resources/output/paella-recipe.md
      }
    }
  }
}

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."
        }
      ]
    },
    "generationConfig": {
      "responseModalities": ["TEXT", "IMAGE"],
      "imageConfig": {
        "aspectRatio": "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 的图片生成功能 (gemini-2.5-flash-image) 除了支持生成图片外,还支持修改图片。Gemini 2.5 Flash Image 支持改进的图片修改和多轮修改,并包含更新的安全过滤器,可提供更灵活、限制更少的用户体验。

它支持以下模态和功能:

  • 图片修改(文本和图片转图片)

    • 提示示例:“修改此图片,使其看起来像卡通图片”
    • 提示示例:[猫的图片] + [枕头的图片] +“请在这只枕头上制作一张我的猫的十字绣图案。”
  • 多轮图片修改(聊天)

    • 提示示例:[上传一张蓝色汽车的图片。]“把这辆车变成敞篷车。”

      • [模型返回了同一场景中敞篷车的图片]“现在将颜色更改为黄色。”
      • [模型返回了一张黄色敞篷车的图片]“添加扰流板。”
      • [模型返回了带扰流板的敞篷车的图片]

修改图片

控制台

如需修改图片,请执行以下操作:

  1. 依次打开 Vertex AI Studio > 创建提示
  2. 点击切换模型,然后从菜单中选择以下模型之一:
    • gemini-2.5-flash-image
    • gemini-3-pro-image-preview
  3. 输出面板中,从下拉菜单中选择图片和文本
  4. 点击插入媒体 (),并从菜单中选择一个来源,然后按照对话框中的说明操作。
  5. 编写提示文本区域中,写下您想对图片进行的修改。
  6. 点击提示 () 按钮。

Gemini 将根据您的说明生成所提供图片的修改版本。此过程需要几秒钟,但可能会相对较慢,具体取决于容量。

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 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_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-3-pro-image-preview",
    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 参考文档

设置环境变量以将 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_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": [
        {"fileData": {
          "mimeType": "image/jpg",
          "fileUri": "FILE_NAME"
          }
        },
        {"text": "Convert this photo to black and white, in a cartoonish style."},
      ]

    },
    "generationConfig": {
      "responseModalities": ["TEXT", "IMAGE"],
      "imageConfig": {
        "aspectRatio": "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 和 Gemini 3 Pro Image 支持改进的多轮修改,让您在收到修改后的图片回答后,可以向模型提供更改意见。这使您可以继续以对话方式修改图片。

请注意,建议将整个请求文件的大小限制为 50MB 以内。

如需测试多轮图片修改,请试用以下笔记本:

如需查看与使用 Gemini 3 Pro Image 进行多轮图片创建和编辑相关的代码示例,请参阅使用思维签名进行多轮图片编辑的示例

Responsible AI

为确保安全可靠的体验,Vertex AI 的图片生成功能采用多层安全防护方法。此功能旨在防止生成不当内容,包括露骨色情、危险、暴力、仇恨或有害内容。

所有用户都必须遵守《生成式 AI 使用限制政策》。此政策严格禁止生成以下内容:

  • 涉及儿童性虐待或性剥削。
  • 宣传暴力极端主义/恐怖主义。
  • 传播未经当事人同意的私密图像。 鼓动自残。
  • 包含露骨色情内容。
  • 构成仇恨言论。
  • 宣扬骚扰或欺凌行为。

如果提示不安全,模型可能会拒绝生成图片,或者提示或生成的回答可能会被我们的安全过滤条件屏蔽。

  • 模型拒绝:如果提示可能不安全,模型可能会拒绝处理相应请求。如果出现这种情况,模型通常会返回一条文本回答,表明无法生成不安全的图片。FinishReason 将为 STOP
  • 安全过滤屏蔽:
    • 如果安全过滤功能将提示识别为可能有害,则 API 会在 PromptFeedback 中返回 BlockedReason
    • 如果安全过滤条件将回答识别为可能有害,则 API 响应将包含 FinishReason(值为 IMAGE_SAFETYIMAGE_PROHIBITED_CONTENT 或类似值)。
    • 如果提示或回答被安全过滤条件屏蔽,finishMessage 字段会包含有关错误代码的更多详细信息。这些代码会映射到有害内容类别:
错误代码 安全类别 说明
89371032
49114662
72817394
11030041
47555161
32549819
51891163
禁止的内容 检测请求中与儿童安全相关的禁止内容。
63429089 色情内容 检测色情性内容。
87332966 危险内容 检测本质上具有潜在危险的内容。
22137204 讨厌的 检测与仇恨相关的主题或内容。
49257518
65344558
名人安全 检测违反 Google 安全政策的名人逼真表示。
14952152 其他 检测请求中的其他各种安全问题。
39322892 人物/人脸 检测因请求设置而不允许的人物或人脸。
17301594 子女 检测因 API 请求设置而不允许的儿童内容。