生成图片

Gemini API 支持使用 Gemini 2.0 Flash 实验版使用 Imagen 3 生成图片。本指南可帮助您开始使用这两种模型。

使用 Gemini 生成图片

Gemini 2.0 Flash Experimental 支持输出文本和内嵌图片。这样,您就可以使用 Gemini 以对话方式编辑图片,或生成包含交织文本的输出内容(例如,在一次对话中生成包含文本和图片的博文)。所有生成的图片都包含 SynthID 水印,Google AI 工作室中的图片也包含可见水印。

以下示例展示了如何使用 Gemini 2.0 生成文本和图片输出:

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
import base64

client = genai.Client()

contents = ('Hi, can you create a 3d rendered image of a pig '
            'with wings and a top hat flying over a happy '
            'futuristic scifi city with lots of greenery?')

response = client.models.generate_content(
    model="gemini-2.0-flash-exp-image-generation",
    contents=contents,
    config=types.GenerateContentConfig(
      response_modalities=['Text', 'Image']
    )
)

for part in response.candidates[0].content.parts:
  if part.text is not None:
    print(part.text)
  elif part.inline_data is not None:
    image = Image.open(BytesIO((part.inline_data.data)))
    image.save('gemini-native-image.png')
    image.show()
const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

async function generateImage() {
  const contents = "Hi, can you create a 3d rendered image of a pig " +
                  "with wings and a top hat flying over a happy " +
                  "futuristic scifi city with lots of greenery?";

  // Set responseModalities to include "Image" so the model can generate  an image
  const model = genAI.getGenerativeModel({
    model: "gemini-2.0-flash-exp-image-generation",
    generationConfig: {
        responseModalities: ['Text', 'Image']
    },
  });

  try {
    const response = await model.generateContent(contents);
    for (const part of  response.response.candidates[0].content.parts) {
      // Based on the part type, either show the text or save the image
      if (part.text) {
        console.log(part.text);
      } else if (part.inlineData) {
        const imageData = part.inlineData.data;
        const buffer = Buffer.from(imageData, 'base64');
        fs.writeFileSync('gemini-native-image.png', buffer);
        console.log('Image saved as gemini-native-image.png');
      }
    }
  } catch (error) {
    console.error("Error generating content:", error);
  }
}

generateImage();
curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp-image-generation:generateContent?key=$GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{
      "parts": [
        {"text": "Hi, can you create a 3d rendered image of a pig with wings and a top hat flying over a happy futuristic scifi city with lots of greenery?"}
      ]
    }],
    "generationConfig":{"responseModalities":["Text","Image"]}
  }' \
  | grep -o '"data": "[^"]*"' \
  | cut -d'"' -f4 \
  | base64 --decode > gemini-native-image.png

该代码示例应输出图片,也可能会输出文本。

AI 生成的奇幻飞猪图片

根据提示和上下文,Gemini 将以不同的模式(文本转图片、文本转图片和文本等)生成内容。下面是一些示例:

  • 文本转图片
    • 示例提示:“生成一张背景为烟花的埃菲尔铁塔图片。”
  • 文本转图片和文本(交织)
    • 示例提示:“生成带插图的西班牙海鲜饭食谱。”
  • 图片和文本转图片和文本(交织)
    • 问题示例:(显示家具齐全的房间的图片)“我的空间适合哪些其他颜色的沙发?您能更新一下图片吗?”
  • 图片编辑(文字和图片转图片)
    • 示例提示:“将此图片编辑成卡通图片”
    • 示例提示:[猫的图片] + [枕头的图片] +“在这个枕头上用十字绣制作我猫的图案。”
  • 多轮图片编辑(聊天)
    • 示例提示:[上传一张蓝色汽车的图片。]“将这辆车改装成敞篷车。”“现在将颜色更改为黄色。”

使用 Gemini 编辑图片

如需执行图片编辑,请添加图片作为输入。以下示例演示了如何上传 base64 编码的图片。对于多张图片和较大的载荷,请参阅图片输入部分。

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO

import PIL.Image

image = PIL.Image.open('/path/to/image.png')

client = genai.Client()

text_input = ('Hi, This is a picture of me.'
            'Can you add a llama next to me?',)

response = client.models.generate_content(
    model="gemini-2.0-flash-exp-image-generation",
    contents=[text_input, image],
    config=types.GenerateContentConfig(
      response_modalities=['Text', 'Image']
    )
)

for part in response.candidates[0].content.parts:
  if part.text is not None:
    print(part.text)
  elif part.inline_data is not None:
    image = Image.open(BytesIO(part.inline_data.data))
    image.show()
const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

async function generateImage() {
    // Load the image from the local file system
    const imagePath = '/path/to/image.png';
    const imageData = fs.readFileSync(imagePath);
    const base64Image = imageData.toString('base64');

    // Prepare the content parts
    const contents = [
        { text: "Hi, This is a picture of me. Can you add a llama next to me?" },
        {
          inlineData: {
            mimeType: 'image/png',
            data: base64Image
          }
        }
      ];

  // Set responseModalities to include "Image" so the model can generate an image
  const model = genAI.getGenerativeModel({
    model: "gemini-2.0-flash-exp-image-generation",
    generationConfig: {
        responseModalities: ['Text', 'Image']
    },
  });

  try {
    const response = await model.generateContent(contents);
    for (const part of  response.response.candidates[0].content.parts) {
      // Based on the part type, either show the text or save the image
      if (part.text) {
        console.log(part.text);
      } else if (part.inlineData) {
        const imageData = part.inlineData.data;
        const buffer = Buffer.from(imageData, 'base64');
        fs.writeFileSync('gemini-native-image.png', buffer);
        console.log('Image saved as gemini-native-image.png');
      }
    }
  } catch (error) {
    console.error("Error generating content:", error);
  }
}

generateImage();
IMG_PATH=/path/to/your/image1.jpeg

if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

IMG_BASE64=$(base64 "$B64FLAGS" "$IMG_PATH" 2>&1)

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp-image-generation:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"contents\": [{
        \"parts\":[
            {\"text\": \"'Hi, This is a picture of me. Can you add a llama next to me\"},
            {
              \"inline_data\": {
                \"mime_type\":\"image/jpeg\",
                \"data\": \"$IMG_BASE64\"
              }
            }
        ]
      }],
      \"generationConfig\": {\"responseModalities\": [\"Text\", \"Image\"]}
    }"  \
  | grep -o '"data": "[^"]*"' \
  | cut -d'"' -f4 \
  | base64 --decode > gemini-edited-image.png

限制

  • 为获得最佳效果,请使用以下语言:英语、西班牙语(墨西哥)、日语、简体中文、印地语。
  • 图片生成功能不支持音频或视频输入。
  • 图片生成功能未必总会触发以下操作:
    • 模型可能只会输出文本。尝试明确要求获取图片输出(例如“生成图片”“随时提供图片”“更新图片”)。
    • 模型可能会在中途停止生成。请重试或尝试使用其他问题。
  • 为图片生成文字时,如果您先生成文字,然后再请求包含文字的图片,Gemini 的效果会最好。

选择模型

您应该使用哪种模型来生成图片?具体取决于您的使用场景。

Gemini 2.0 最适合生成与上下文相关的图片、混合文本和图片、纳入世界知识以及推理图片。您可以使用它在长篇幅文本序列中嵌入准确且与上下文相关的视觉内容。您还可以使用自然语言以对话方式编辑图片,同时在整个对话过程中保持上下文。

如果图片质量是您的首要考虑因素,那么 Imagen 3 是更好的选择。Imagen 3 擅长于打造逼真的效果、艺术细节,以及印象派或动漫等特定艺术风格。Imagen 3 还非常适合执行专门的图片编辑任务,例如更新商品背景、放大图片以及为视觉内容注入品牌和风格。您可以使用 Imagen 3 制作徽标或其他品牌产品设计。

使用 Imagen 3 生成图片

Gemini API 提供对 Imagen 3 的访问权限,该模型是 Google 质量最高的文本转图像模型,具有许多新功能和改进功能。Imagen 3 可以执行以下操作:

  • 与之前的模型相比,生成的图片细节更丰富、光线更丰富,干扰性伪影更少
  • 理解用自然语言编写的提示
  • 生成各种格式和风格的图片
  • 比之前的模型更有效地渲染文本

Imagen 示例

本部分介绍了如何实例化 Imagen 模型并生成图片。

安装 Google Gen AI SDK 后,您可以使用以下代码生成图片:

PythonREST
from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO

client = genai.Client(api_key='GEMINI_API_KEY')

response = client.models.generate_images(
    model='imagen-3.0-generate-002',
    prompt='Fuzzy bunnies in my kitchen',
    config=types.GenerateImagesConfig(
        number_of_images= 4,
    )
)
for generated_image in response.generated_images:
  image = Image.open(BytesIO(generated_image.image.image_bytes))
  image.show()
curl -X POST \
    "https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-002:predict?key=GEMINI_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
        "instances": [
          {
            "prompt": "Fuzzy bunnies in my kitchen"
          }
        ],
        "parameters": {
          "sampleCount": 4
        }
      }'

代码示例应输出四张类似于此图像的图片:

AI 生成的图片:厨房里有两只毛茸茸的兔子

您还可以尝试使用 Gemini 实战宝典中的 “Imagen 使用入门”笔记本

Imagen 模型参数

generate_images() 提供以下参数:

  • prompt:图片的文本提示。
  • number_of_images:要生成的图片数量,介于 1 到 4(包括这两个数值)之间。默认值为 4。
  • aspect_ratio:更改生成图片的宽高比。支持的值包括 "1:1""3:4""4:3""9:16""16:9"。默认值为 "1:1"
  • safety_filter_level:为安全性过滤策略添加过滤级别。以下值均有效:
    • "BLOCK_LOW_AND_ABOVE":当概率得分或严重程度得分为 LOWMEDIUMHIGH 时屏蔽。
    • "BLOCK_MEDIUM_AND_ABOVE":当概率得分或严重程度得分为 MEDIUMHIGH 时屏蔽。
    • "BLOCK_ONLY_HIGH":当概率得分或严重级别得分为 HIGH 时屏蔽。
  • person_generation:允许模型生成人物图片。支持以下值:
    • "DONT_ALLOW":禁止生成人物图片。
    • "ALLOW_ADULT":生成成人图像,但不生成儿童图像。 这是默认值。

系统始终会向生成的图片添加不可见的数字 SynthID 水印。

文本提示语言

支持以下输入文本提示语言:

  • 英语 (en)

后续步骤