Gemini 可以通过对话方式生成和处理图片。您可以通过文本、图片或两者结合的方式向 Gemini 发出提示,以完成各种与图片相关的任务,例如图片生成和编辑。所有生成的图片都包含 SynthID 水印。
图片生成功能可能未在所有地区和国家/地区推出,如需了解详情,请参阅我们的 Gemini 模型页面。
图片生成(根据文本生成图片)
以下代码演示了如何根据描述性提示生成图片。您必须在配置中添加 responseModalities
:["TEXT", "IMAGE"]
。这些模型不支持仅输出图片。
Python
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-preview-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()
JavaScript
import { GoogleGenAI, Modality } from "@google/genai";
import * as fs from "node:fs";
async function main() {
const ai = new GoogleGenAI({});
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 response = await ai.models.generateContent({
model: "gemini-2.0-flash-preview-image-generation",
contents: contents,
config: {
responseModalities: [Modality.TEXT, Modality.IMAGE],
},
});
for (const part of 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");
}
}
}
main();
Go
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
ResponseModalities: []string{"TEXT", "IMAGE"},
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.0-flash-preview-image-generation",
genai.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?"),
config,
)
for _, part := range result.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
imageBytes := part.InlineData.Data
outputFilename := "gemini_generated_image.png"
_ = os.WriteFile(outputFilename, imageBytes, 0644)
}
}
}
REST
curl -s -X POST
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-preview-image-generation:generateContent" \
-H "x-goog-api-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

图片编辑(文字和图片转图片)
如需执行图片编辑,请添加图片作为输入内容。以下示例演示了如何上传 base64 编码的图片。对于多张图片和更大的载荷,请参阅图片输入部分。
Python
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-preview-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()
JavaScript
import { GoogleGenAI, Modality } from "@google/genai";
import * as fs from "node:fs";
async function main() {
const ai = new GoogleGenAI({});
// 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: "Can you add a llama next to the image?" },
{
inlineData: {
mimeType: "image/png",
data: base64Image,
},
},
];
// Set responseModalities to include "Image" so the model can generate an image
const response = await ai.models.generateContent({
model: "gemini-2.0-flash-preview-image-generation",
contents: contents,
config: {
responseModalities: [Modality.TEXT, Modality.IMAGE],
},
});
for (const part of 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");
}
}
}
main();
Go
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
imagePath := "/path/to/image.png"
imgData, _ := os.ReadFile(imagePath)
parts := []*genai.Part{
genai.NewPartFromText("Hi, This is a picture of me. Can you add a llama next to me?"),
&genai.Part{
InlineData: &genai.Blob{
MIMEType: "image/png",
Data: imgData,
},
},
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
config := &genai.GenerateContentConfig{
ResponseModalities: []string{"TEXT", "IMAGE"},
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.0-flash-preview-image-generation",
contents,
config,
)
for _, part := range result.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
imageBytes := part.InlineData.Data
outputFilename := "gemini_generated_image.png"
_ = os.WriteFile(outputFilename, imageBytes, 0644)
}
}
}
REST
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-preview-image-generation:generateContent" \
-H "x-goog-api-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 的效果会更好。
- 在某些地区/国家/地区,无法使用图片生成功能。 如需了解详情,请参阅模型。
何时使用 Imagen
除了使用 Gemini 的内置图片生成功能外,您还可以通过 Gemini API 访问我们专门的图片生成模型 Imagen。
在以下情况下选择 Gemini:
- 您需要利用世界知识和推理能力生成具有上下文相关性的图片。
- 无缝融合文字和图片非常重要。
- 您希望在长文本序列中嵌入准确的视觉元素。
- 您希望在保持上下文的情况下以对话方式修改图片。
在以下情况下,请选择 Imagen:
- 图片质量、写实度、艺术细节或特定风格(例如印象派、动漫)是首要考虑因素。
- 执行专业编辑任务,例如更新商品背景或放大图片。
- 融入品牌元素、风格,或生成徽标和产品设计。
Imagen 4 应该是您开始使用 Imagen 生成图片的首选模型。对于高级使用情形或需要最佳图片质量时,请选择 Imagen 4 Ultra。请注意,Imagen 4 Ultra 每次只能生成一张图片。