Gemini API
開發文件:Nano Banana image generation。重點只有一個:影像模型和文字模型走同一個 generate_content,不是另一套 Imagen 專用 endpoint。
最小範例(文生圖)
安裝 google-genai,設定 GOOGLE_API_KEY:
from google import genai
client = genai.Client()
prompt = (
"Create a picture of a nano banana dish in a fancy "
"restaurant with a Gemini theme"
)
response = client.models.generate_content(
model="gemini-3.1-flash-image",
contents=[prompt],
)
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")
Pro 把 model 換成文件上的 gemini-3-pro-image。長寬比、解析度用 GenerateContentConfig/ImageConfig(aspect_ratio、image_size),細節以當下 API 文件為準。
修圖與多輪
把 PIL/檔案圖片和文字一起放進 contents,就是圖+文修圖。多輪則用 client.chats.create 開聊天,同一 session 連續送「只改背景」「把字改正確」。官方 DevByte 逐步示範這三段:生圖、編輯、多圖輸入、聊天式編輯。
舊文常寫 gemini-2.5-flash-image-preview 或 response_modalities=["IMAGE"]。新專案請對過最新文件,不要從 2025 年部落格整段複製。
相關影音
Google for Developers 約 11 分鐘:AI Studio 原型 → 專案與 SDK → 生圖/修圖/多圖/chat session。
對應文章:How to Build with Nano Banana(若連結改版,從影片說明的 goo.gle 進入)。