Skip to content
LangChain4j 文档版本 1.22.0 源快照 c7735cab 更新于 2026-10-14

Google AI Gemini 图像生成

Gemini 能以对话方式生成和编辑图像,使用被称为 Nano Banana(Gemini 2.5 Flash Image)与 Nano Banana Pro(Gemini 3 Pro Image Preview)的专用图像模型。

目录

概述

Gemini 的原生图像生成能力让你能够:

  • 文生图:从文本描述生成高质量图像
  • 图像编辑:在已有图像中添加、移除或修改元素
  • 风格迁移:为图像应用艺术风格
  • 迭代精炼:通过多轮对话式地精炼图像
  • 高保真文本渲染:生成带有清晰、排版良好文字的图像

所有生成的图像都带有 SynthID 水印。

可用模型

模型描述最大分辨率最大输入图像数
gemini-2.5-flash-image快速、高效的图像生成(Nano Banana)1024px3
gemini-3-pro-image-preview高级特性、思考模式、Google 搜索接地(Nano Banana Pro)4K14

GoogleAiGeminiImageModel

基本用法

java
ImageModel imageModel = GoogleAiGeminiImageModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-2.5-flash-image")
    .build();

Response<Image> response = imageModel.generate(
    "A nano banana dish in a fancy restaurant with a Gemini theme"
);

// Save the generated image
Image image = response.content();
byte[] imageBytes = Base64.getDecoder().decode(image.base64Data());
Files.write(Paths.get("nano-banana.png"), imageBytes);

配置

java
ImageModel imageModel = GoogleAiGeminiImageModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-3-pro-image-preview")
    .aspectRatio("16:9")              // Output aspect ratio
    .imageSize("2K")                   // Resolution (Gemini 3 Pro only)
    .timeout(Duration.ofSeconds(120))
    .maxRetries(3)
    .logRequestsAndResponses(true)
    .safetySettings(...)               // Content safety settings
    .build();

图像生成

文生图

从描述性文本提示词生成图像:

java
ImageModel imageModel = GoogleAiGeminiImageModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-2.5-flash-image")
    .build();

// Photorealistic style
Response<Image> photo = imageModel.generate("""
    A photorealistic close-up portrait of an elderly Japanese ceramicist
    with deep wrinkles and a warm smile, inspecting a tea bowl.
    Soft golden hour light, 85mm portrait lens, shallow depth of field.
    """);

// Stylized illustration
Response<Image> sticker = imageModel.generate("""
    A kawaii-style sticker of a happy red panda wearing a bamboo hat,
    munching on a leaf. Bold outlines, cel-shading, vibrant colors,
    white background.
    """);

// Logo design
Response<Image> logo = imageModel.generate("""
    A modern, minimalist logo for 'The Daily Grind' coffee shop.
    Clean, bold sans-serif font. Black and white. Circular design
    with a clever coffee bean element.
    """);

宽高比

两个模型都支持的宽高比:

宽高比使用场景
1:1方形,社交媒体帖子
2:3、3:2竖版/横版照片
3:4、4:3标准照片
4:5、5:4Instagram 帖子
9:16、16:9快拍、YouTube 缩略图
21:9电影感、超宽屏
java
ImageModel imageModel = GoogleAiGeminiImageModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-2.5-flash-image")
    .aspectRatio("16:9")  // Widescreen format
    .build();

图像尺寸

Gemini 3 Pro Image Preview 支持更高分辨率:

尺寸描述
1K默认分辨率
2K更高分辨率
4K最高分辨率
java
ImageModel imageModel = GoogleAiGeminiImageModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-3-pro-image-preview")
    .aspectRatio("1:1")
    .imageSize("4K")  // High resolution output
    .build();

图像编辑

添加与移除元素

通过连同文本提示词一并提供图像来编辑已有图像:

java
ImageModel imageModel = GoogleAiGeminiImageModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-2.5-flash-image")
    .build();

// Load the source image
Image sourceImage = Image.builder()
    .base64Data(Base64.getEncoder().encodeToString(
        Files.readAllBytes(Paths.get("cat.png"))))
    .mimeType("image/png")
    .build();

Response<Image> edited = imageModel.edit(
    sourceImage,
    "Add a small wizard hat on the cat's head. " +
    "Make it look natural with matching lighting."
);

风格迁移

将图像转换为不同的艺术风格:

java
Image cityPhoto = // ... load your image

Response<Image> stylized = imageModel.edit(
    cityPhoto,
    "Transform this city street into Vincent van Gogh's 'Starry Night' style. " +
    "Preserve the composition but render with swirling brushstrokes " +
    "and a dramatic palette of deep blues and bright yellows."
);

局部重绘

在保留其余部分的同时修改特定元素:

java
Image livingRoom = // ... load your image

Response<Image> edited = imageModel.edit(
    livingRoom,
    "Change only the blue sofa to a vintage brown leather chesterfield. " +
    "Keep everything else exactly the same."
);

批量图像生成

要大规模生成多张图像并节省 50% 成本:

java
GoogleAiGeminiBatchImageModel batchModel = GoogleAiGeminiBatchImageModel.builder()
    .apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
    .modelName("gemini-2.5-flash-image")
    .build();

List<String> prompts = List.of(
    "A nano banana dish in a Gemini-themed restaurant",
    "A kawaii sticker of a banana wearing a chef hat",
    "A photorealistic banana split dessert",
    "A minimalist logo for 'Nano Banana Co.'"
);

// Submit batch
BatchResponse<Response<Image>> response = batchModel.submit(GeminiBatchRequest.from(
    prompts, "image-batch"));
String batchId = response.batchId();

// Poll for completion
while (!response.state().isTerminal()) {
    Thread.sleep(10000);
    response = batchModel.retrieve(batchId);
}

// Process results
if (response.state() == BatchState.SUCCEEDED) {
    for (Response<Image> imageResponse : response.responses()) {
        Image image = imageResponse.content();
        byte[] imageBytes = Base64.getDecoder().decode(image.base64Data());
        // Save or process each image
    }
}

// Clean up
batchModel.deleteBatchJob(batchId);

responses() 与 errors() 是扁平的便捷视图(永不为 null,无可上报时为空),它们不会告诉你是哪个提示词产生了哪张图像。要将每个结果映射回其提示词,请使用 results():它每个请求返回一个 BatchItemResult,顺序与提交的提示词一致,每个要么是 BatchItemResult.Success(含 response()),要么是 BatchItemResult.Failure(含 error()):

java
List<BatchItemResult<Response<Image>>> results = response.results();
for (int i = 0; i < results.size(); i++) {
    BatchItemResult<Response<Image>> item = results.get(i);
    if (item.isSuccess()) {
        Image image = item.response().content();
        // Save or process the image generated for prompts.get(i)
    } else {
        BatchError error = item.error();
        System.err.println("Prompt #" + i + " failed: " + error.code() + " - " + error.message());
    }
}

限制

  • 语言:以 EN 表现最佳,支持的语言包括 ar-EG、de-DE、es-MX、fr-FR、hi-IN、id-ID、it-IT、ja-JP、ko-KR、pt-BR、ru-RU、vi-VN、zh-CN
  • 输入:图像生成不支持音频与视频输入
  • 输出数量:模型不一定总能生成所请求的确切图像数量
  • 输入图像:
    • gemini-2.5-flash-image:最多 3 张输入图像
    • gemini-3-pro-image-preview:最多 14 张输入图像(含 5 张用于一致性的人物图像)
  • URL 图像:编辑不支持基于 URL 的图像;请使用 base64 编码的图像
  • 水印:所有生成的图像都带有 SynthID 水印

资源

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。