资讯动态

Gemini API 媒体生成完全指南:图像生成、图像编辑与视频生成实战

发布时间:2026/9/13 21:14:15 来源:尧图企业网站定制
Gemini API 媒体生成完全指南图像生成、图像编辑与视频生成实战【免费下载链接】skillsAgent Skills for Google products and technologies项目地址: https://gitcode.com/GitHub_Trending/skills29/skills导读本文以 skills29 仓库中 gemini-api 技能的 media_generation.md 为核心系统讲解在 Gemini Enterprise Agent Platform 上使用 Google Gen AI SDKgoogle-genai进行图像生成、图像编辑与视频生成Gemini Omni 与 Veo的完整实战方案。你将掌握generate_content、chats、interactions.create、generate_videos四类媒体能力调用方式、关键配置参数ImageConfig、VideoConfig、VideoResponseFormat、GenerateVideosConfig以及结果提取与落地存储的最佳实践。环境准备与模型选型客户端初始化统一使用 Google Gen AI SDK初始化客户端时优先依赖环境变量Application Default Credentials / Express Mode API Key相关要求详见 gemini-api 技能主文档# ADC 模式企业级 Agent Platform export GOOGLE_CLOUD_PROJECTyour-project-id export GOOGLE_CLOUD_LOCATIONglobal export GOOGLE_GENAI_USE_ENTERPRISEtrue # 或 Express ModeAPI Key export GOOGLE_API_KEYyour-api-key export GOOGLE_GENAI_USE_ENTERPRISEtruefrom google import genai from google.genai import types client genai.Client()媒体生成相关模型根据 SKILL.md 的 Models 章节模型定位适用场景gemini-3-pro-imageNano Banana Pro高质量图像生成与编辑高分辨率海报、产品图、精细编辑gemini-3.1-flash-imageNano Banana 2中等质量图像生成与编辑日常快速出图gemini-3.1-flash-lite-imageNano Banana 2 Lite快速图像生成与编辑高吞吐、轻量任务gemini-omni-flash-preview视频生成与编辑Preview文生视频、图生视频、参考生视频、视频编辑veo-3.1-fast-generate-001Veo 视频生成快速模型低成本视频生成质量通常足够注意gemini-2.5-*、gemini-2.0-*、gemini-1.x-*等旧模型已弃用不应在新项目中使用。图像生成Image Generation使用 gemini-3.1-flash-image 生成图像图像生成通过generate_content完成结果以inline_data形式返回可用part.as_image()转为 PIL Image 并保存from google import genai from google.genai import types client genai.Client() response client.models.generate_content( modelgemini-3.1-flash-image, contentsA dog reading a newspaper, ) for part in response.parts: if part.text is not None: print(part.text) elif part.inline_data is not None: image part.as_image() image.save(generated_image.png)关键点响应中的每个part要么是文本说明part.text要么是二进制图像数据part.inline_data。必须同时处理两种情况不能假设响应只有一种类型。使用 gemini-3-pro-image 生成高分辨率图像需要高清输出时切换到gemini-3-pro-image并通过ImageConfig控制画面比例与分辨率from google import genai from google.genai import types client genai.Client() response client.models.generate_content( modelgemini-3-pro-image, contentsA dog reading a newspaper, configtypes.GenerateContentConfig( image_configtypes.ImageConfig(aspect_ratio16:9, image_size2K) ), ) for part in response.parts: if part.text is not None: print(part.text) elif part.inline_data is not None: image part.as_image() image.save(generated_image.png)ImageConfig关键参数参数取值示例说明aspect_ratio16:9、9:16、1:1等输出图像宽高比按构图需求选择image_size2K等输出分辨率档位2K表示高分辨率结合 SKILL.md 的模型推荐gemini-3-pro-image专为高质量输出设计适合对细节要求高的场景。图像编辑Image Editing图像编辑推荐使用chat 模式把待编辑图像作为消息发送给模型模型基于上下文进行修改且可在同一会话中持续迭代。需要Pillow库加载本地图像from google import genai from PIL import Image client genai.Client() prompt A small white ceramic bowl with lemons and limes image Image.open(fruit.png) # 创建 chat 会话 chat client.chats.create(modelgemini-3.1-flash-image) # 发送图像并请求编辑 response chat.send_message([prompt, image]) # 提取文本与生成的图像 for i, part in enumerate(response.candidates[0].content.parts): if part.text is not None: print(part.text) elif part.inline_data is not None: image part.as_image() image.save(fgenerated_image_{i}.png) # 继续迭代编辑 chat.send_message(Make the bowl blue)要点send_message的入参是一个列表[prompt, image]PIL Image 对象会被 SDK 自动编码为图像 part结果遍历的是response.candidates[0].content.parts每次可能返回多个 part按顺序保存为generated_image_0.png、generated_image_1.pngchat 会话保留历史上下文可直接追加新指令继续编辑无需重新发送原图。使用 Gemini Omni 生成与编辑视频gemini-omni-flash-previewPreview 版本支持从文本、图像、参考媒体生成视频并可进行视频编辑输出为720p 且带有同步音频。与 Veo 不同Omni 走Interactions APIclient.interactions.create而不是generate_content/generate_videos。注意输出视频默认内嵌 C2PA 内容凭证元数据与 SynthID 数字水印视频伴随生成同步音频分辨率为 720p。使用前请务必查看定价该模型使用成本可能较高。核心配置Interactions API 的媒体配置通过generation_config.video_config与response_format控制任务类型interactions.VideoConfig.tasktext_to_video、image_to_video、reference_to_video、edit必须与输入类型和期望行为匹配响应格式interactions.VideoResponseFormataspect_ratio16:9或9:16、duration3s–10s、delivery。这些参数也可以直接写在文本 prompt 中交付方式delivery设为uri并配合gcs_urigs://GCS_BUCKET将结果保存到 Cloud Storage否则视频字节以 base64 内联返回。响应以interaction.steps形式返回需要收集每个model_outputstep 中的content。文档提供了一个通用提取辅助函数import base64 from google import genai from google.genai import interactions client genai.Client() omni_model gemini-omni-flash-preview def save_video(interaction, pathoutput.mp4): contents [] for step in interaction.steps: if step.type model_output: contents.extend(step.content) with open(path, wb) as f: f.write(base64.b64decode(contents[0].data))这与 gemini-interactions-api 技能 中描述的steps数据模型一致model_output类型的 step 内含content数组视频以 base64data承载。文本生成视频Text-to-video纯文本 prompt 生成视频任务类型为text_to_videoprompt A hard-shell suitcase rolling down a city street at sunset, cinematic tracking shot. interaction client.interactions.create( modelomni_model, inputprompt, generation_configinteractions.GenerationConfig( video_configinteractions.VideoConfig(tasktext_to_video) ), response_formatinteractions.VideoResponseFormat( aspect_ratio16:9, duration9s, # deliveryuri, # gcs_urigs://GCS_BUCKET, ), ) save_video(interaction)将delivery与gcs_uri的注释打开即可把视频直接写入指定的 Cloud Storage 桶避免大体积 base64 在客户端与网络间传输。图像生成视频Image-to-video提供一张起始图像作为视频的字面第一帧。图像既可以 base64 内联传入也可以用 Cloud Storageuri传入prompt The suitcase stands up, unzips, and colorful travel stickers pop out around it. with open(suitcase.png, rb) as f: img_b64 base64.b64encode(f.read()).decode(utf-8) interaction client.interactions.create( modelomni_model, input[ {type: text, text: prompt}, {type: image, mime_type: image/png, data: img_b64}, ], generation_configinteractions.GenerationConfig( video_configinteractions.VideoConfig(taskimage_to_video) ), ) save_video(interaction)输入结构为{type: ...}字典列表文本为{type: text, text: ...}图像为{type: image, mime_type: ..., data: ...}。参考媒体生成视频Reference-to-video提供参考图像例如角色、产品来引导生成。与 image-to-video 的区别在于参考媒体是风格/主体引导而不是字面的第一帧。当前版本不支持视频和音频参考输入prompt A woman walks up to the arcade game and starts playing. 9:16 aspect ratio. 7 second video. images_input [] for img_path in [woman.jpeg, arcade-game.png]: with open(img_path, rb) as f: img_b64 base64.b64encode(f.read()).decode(utf-8) images_input.append({type: image, mime_type: image/jpeg, data: img_b64}) interaction client.interactions.create( modelomni_model, input[{type: text, text: prompt}, *images_input], generation_configinteractions.GenerationConfig( video_configinteractions.VideoConfig(taskreference_to_video) ), ) save_video(interaction)注意这里 prompt 直接内嵌了9:16 aspect ratio与7 second video等格式要求印证了格式参数也可直接写在文本 prompt 中的说明。视频编辑Video editing在源视频上添加、移除或改变物体或进行风格重绘。源视频必须短于 10 秒也可以附带参考图像来引导编辑。视频输入支持 Cloud Storageuriprompt Change the dog to a cat, remove the backpack, and add a propeller hat. interaction client.interactions.create( modelomni_model, input[ {type: text, text: prompt}, {type: image, mime_type: image/png, uri: gs://cloud-samples-data/generative-ai/image/chair-cat.png}, {type: video, mime_type: video/mp4, uri: gs://cloud-samples-data/generative-ai/video/dog_day1.mp4}, ], generation_configinteractions.GenerationConfig( video_configinteractions.VideoConfig(taskedit) ), ) save_video(interaction)视频 part 的结构为{type: video, mime_type: video/mp4, uri: gs://...}通过uri引用 GCS 中的源视频。异步生成Async generation视频生成耗时较长可设置backgroundTrue提交后台任务之后用client.interactions.get轮询状态import time initial client.interactions.create(modelomni_model, inputprompt, backgroundTrue) interaction initial while interaction.status not in [completed, failed]: time.sleep(10) interaction client.interactions.get(idinitial.id) if interaction.status completed: save_video(interaction)轮询状态包含completed与failed两种终态建议在循环中同时处理异常或超时。多轮编辑Chat 模式通过把上一轮interaction.steps重新传回input并追加新的用户输入 turn实现迭代式视频精修interaction1 client.interactions.create( modelomni_model, inputA claymation ball character rolling and then being stopped by a wall, stop motion., ) turn2_input interaction1.steps [ {type: user_input, content: [{type: text, text: Now make the same video in a doodle style.}]} ] interaction2 client.interactions.create(modelomni_model, inputturn2_input) save_video(interaction2)新增的用户 turn 使用{type: user_input, content: [{type: text, text: ...}]}结构这与 gemini-interactions-api 技能 中user_inputstep 的类型约定完全一致。兼容性提示本仓库中 gemini-interactions-api 技能 说明在 Gemini Enterprise Agent Platform 上 Interactions API 尚不支持直接指定基础模型model...需改用已部署的 agentagentAGENT_ID而model...在 ai.google.dev 等其他 Gemini API 场景下仍然有效。若在 Agent Platform 上使用 Omni 视频生成遇到模型调用报错请优先检查是否需要切换为已配置的 agent 目标。使用 Veo 生成视频Veo 的使用成本较高建议先确认 Veo 定价优先使用快速模型veo-3.1-fast-generate-001其输出质量通常已足够必要时再切换更大模型。视频生成是异步操作返回一个 operationimport time from google import genai from google.genai import types from PIL import Image client genai.Client() image Image.open(image.png) # 可选起始图像 # 视频生成是异步操作 operation client.models.generate_videos( modelveo-3.1-fast-generate-001, prompta cat reading a book, imageimage, configtypes.GenerateVideosConfig( person_generationdont_allow, aspect_ratio16:9, number_of_videos1, duration_seconds5, output_gcs_urigs://your-bucket/your-prefix, ), ) # 轮询直到完成 while not operation.done: time.sleep(20) operation client.operations.get(operation) if operation.response: print(operation.result.generated_videos[0].video.uri)GenerateVideosConfig关键参数参数示例说明person_generationdont_allow/allow_all/allow_adult控制人物生成策略dont_allow禁止生成人物aspect_ratio16:9输出画面比例number_of_videos1一次生成视频数量duration_seconds5视频时长秒output_gcs_urigs://bucket/prefix结果写入的 Cloud Storage 路径与 Omni 通过interactions返回 base64 不同Veo 的结果通过 operation 轮询获取最终视频 URI 位于operation.result.generated_videos[0].video.uri通常直接指向 GCS。总结与最佳实践按模型选 API图像生成/编辑用generate_contentchatsOmni 视频用interactions.create响应在steps中Veo 视频用generate_videos operation 轮询任务与格式参数匹配Omni 的VideoConfig.task必须与输入媒体类型一一对应text_to_video、image_to_video、reference_to_video、edit格式也可写在 prompt 文本中大结果落 GCSOmni 设置deliveryurigcs_uriVeo 设置output_gcs_uri避免大体积视频以 base64 往返传输人物合规Veo 使用person_generationdont_allow控制人物生成遵守负责任 AI 策略迭代编辑优先 chat图像编辑与视频多轮精修都支持上下文延续善用会话式 API 可以大幅减少重复输入关注平台差异Agent Platform 上 Interactions API 可能需要以agent替代model目标部署前参考 gemini-interactions-api 与 gemini-agents-api 的技能说明。更多关联能力文本与多模态输入、结构化输出、Live API 等可查阅 gemini-api 技能 及其 references 目录其中 text_and_multimodal.md 提供了图像、音频、视频作为输入的完整示例可作为媒体生成的输入侧补充。【免费下载链接】skillsAgent Skills for Google products and technologies项目地址: https://gitcode.com/GitHub_Trending/skills29/skills创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价