使用 Gemini 生成图片

Gemini 2.0 Flash 支持多种模态的回答生成,包括文本和图片。

图片生成

Gemini 2.0 Flash 的图片生成公开预览版 (gemini-2.0-flash-preview-image-generation) 支持生成图片和文本。这可扩展 Gemini 的功能,使其能够执行以下操作:

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

在此公开实验版中,Gemini 2.0 Flash 可以生成 1024 像素的图片,支持生成和修改人物图片,并包含更新的安全过滤条件,可提供更灵活、限制更少的用户体验.

它支持以下模态和功能:

  • 文本到图像

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

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

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

    • 提示示例:(附带一张带家具的房间的照片)“我的空间还适合放置哪些颜色的沙发?Can you update the image?”
  • 图片编辑(文字和图片转图片)

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

    • 提示示例:[上传一张蓝色汽车的图片。]“把这辆车变成敞篷车。”“现在将颜色更改为黄色。”

限制:

  • 为获得最佳性能,请使用以下语言:英语、西班牙语(墨西哥)、日语(日本)、中文(中国)、印地语(印度)。
  • 图片生成功能不支持音频或视频输入。
  • 图片生成功能可能不会始终触发:
    • 模型可能只能输出文本。尝试明确要求生成图片输出。例如,“在您操作过程中提供图片”。
    • 模型可能会以图片形式生成文本。尝试明确要求文本输出。例如,“生成叙事文本以及插图”。
    • 模型可能会中途停止生成。请重试或尝试使用其他提示。

生成图片

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

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

控制台

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

  1. 打开 Vertex AI Studio > 创建提示
  2. 点击切换模型,然后从菜单中选择 gemini-2.0-flash-preview-image-generation
  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-2.0-flash-preview-image-generation",
    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("example-image.png")
# Example response:
#   A beautiful photograph captures the iconic Eiffel Tower in Paris, France,
#   against a backdrop of a vibrant and dynamic fireworks display. The tower itself...

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 将根据您的描述生成图片。此过程应需要几秒钟,但可能会相对较慢,具体取决于容量。

修改图片

控制台

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

  1. 打开 Vertex AI Studio > 创建提示
  2. 点击切换模型,然后从菜单中选择 gemini-2.0-flash-preview-image-generation
  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("example-image.png")

response = client.models.generate_content(
    model="gemini-2.0-flash-exp",
    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("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.
#  ....

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"],
    },
    "safetySettings": {
      "method": "PROBABILITY",
      "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
      "threshold": "BLOCK_MEDIUM_AND_ABOVE"
    },
  }' 2>/dev/null >response.json

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

生成图文交织的内容

Gemini 2.0 Flash 可以在文本回答中穿插生成图片。例如,您可以生成生成的食谱中每个步骤的图片,以便与该步骤的文本搭配使用,而无需单独向模型发出请求。

控制台

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

  1. 打开 Vertex AI Studio > 创建提示
  2. 点击切换模型,然后从菜单中选择 gemini-2.0-flash-preview-image-generation
  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-2.0-flash-exp",
    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("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"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 将根据您的描述生成图片。此过程应需要几秒钟,但可能会相对较慢,具体取决于容量。