from google import genaifrom google.genai import typesfrom PIL import Imageimport osclient = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"),)response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents="Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme", config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ),)final_image = Nonefor part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif part.inline_data is not None: final_image = part.as_image()if final_image: final_image.save("generated_image.png") print("Image saved to generated_image.png")
import { GoogleGenAI } from "@google/genai";import * as fs from "fs";const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" },});const response = await ai.models.generateContent({ model: "gemini-3.1-flash-image-preview", contents: "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme", config: { responseModalities: ["TEXT", "IMAGE"] },});let finalImagePart;for (const part of response.candidates[0].content.parts) { if (part.thought === true) { continue; } if (part.text) { console.log(part.text); } if (part.inlineData) { finalImagePart = part; }}if (finalImagePart) { const buffer = Buffer.from(finalImagePart.inlineData.data, "base64"); fs.writeFileSync("generated_image.png", buffer); console.log("Image saved to generated_image.png");}
curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "parts": [{"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}] }], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"] } }'
保存最终图像部分:图像数据位于 candidates[0].content.parts 中,其中可能包含文本和/或图像部分。Gemini 图像模型也可能在最终图像之前返回中间思考部分,尤其是在你同时请求文本和图像,或显式启用思考输出时。不要盲目保存第一个 inlineData;跳过 thought 为 true 的部分,然后保存最后一个剩余的图像部分。仅包含最终图像的典型响应:
from google import genaifrom google.genai import typesfrom PIL import Imageimport osclient = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"),)# Load the source imagesource_image = Image.open("source.jpg")response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents=["Transform this into a watercolor painting", source_image], config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ),)final_image = Nonefor part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif part.inline_data is not None: final_image = part.as_image()if final_image: final_image.save("watercolor_output.png")
import { GoogleGenAI } from "@google/genai";import * as fs from "fs";const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" },});const imageData = fs.readFileSync("source.jpg").toString("base64");const response = await ai.models.generateContent({ model: "gemini-3.1-flash-image-preview", contents: [ { text: "Transform this into a watercolor painting" }, { inlineData: { mimeType: "image/jpeg", data: imageData } }, ], config: { responseModalities: ["TEXT", "IMAGE"] },});const imageParts = response.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true,);const finalImagePart = imageParts.at(-1);if (finalImagePart) { fs.writeFileSync("watercolor_output.png", Buffer.from(finalImagePart.inlineData.data, "base64"));}
from google import genaifrom google.genai import typesfrom PIL import Imageimport osclient = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"),)collage = Image.open("collage.jpg")response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents=[ "A model is posing and leaning against a pink BMW with a green alien keychain attached to a pink handbag, a pink parrot on her shoulder, and a pug wearing a pink collar and gold headphones", collage, ], config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ),)final_image = Nonefor part in response.parts: if getattr(part, "thought", False): continue if part.inline_data is not None: final_image = part.as_image()if final_image: final_image.save("composition_output.png")
curl -s -X POST \ "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \ -H "Authorization: Bearer $COMETAPI_KEY" \ -H "Content-Type: application/json" \ -d '{ "contents": [{ "role": "user", "parts": [ { "text": "A model is posing and leaning against a pink BMW with a green alien keychain attached to a pink handbag, a pink parrot on her shoulder, and a pug wearing a pink collar and gold headphones" }, { "inline_data": { "mime_type": "image/jpeg", "data": "<base64-encoded-collage-image>" } } ] }], "generationConfig": { "responseModalities": ["TEXT", "IMAGE"] } }'
方法 2:多张独立图片 (最多 14 张)
直接传入多张图片。Gemini 3 模型最多支持 14 张参考图片(物体 + 角色):
from google import genaifrom google.genai import typesfrom PIL import Imageimport osclient = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"),)image1 = Image.open("image1.jpg")image2 = Image.open("image2.jpg")image3 = Image.open("image3.jpg")response = client.models.generate_content( model="gemini-3.1-flash-image-preview", contents=["Merge the three images", image1, image2, image3], config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ),)final_image = Nonefor part in response.parts: if getattr(part, "thought", False): continue if part.inline_data is not None: final_image = part.as_image()if final_image: final_image.save("merged_output.png")
from google import genaifrom google.genai import typesimport osclient = genai.Client( http_options={"api_version": "v1beta", "base_url": "https://api.cometapi.com"}, api_key=os.environ.get("COMETAPI_KEY"),)chat = client.chats.create( model="gemini-3.1-flash-image-preview", config=types.GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ),)## First turn: Generateresponse = chat.send_message( "Create a vibrant infographic explaining photosynthesis as a recipe, styled like a colorful kids cookbook")final_image = Nonefor part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif image := part.as_image(): final_image = imageif final_image: final_image.save("photosynthesis.png")## Second turn: Refineresponse = chat.send_message("Update this infographic to be in Spanish. Do not change any other elements.")final_image = Nonefor part in response.parts: if getattr(part, "thought", False): continue if part.text is not None: print(part.text) elif image := part.as_image(): final_image = imageif final_image: final_image.save("photosynthesis_spanish.png")
import { GoogleGenAI } from "@google/genai";import * as fs from "fs";const ai = new GoogleGenAI({ apiKey: process.env.COMETAPI_KEY, httpOptions: { apiVersion: "v1beta", baseUrl: "https://api.cometapi.com" },});const chat = ai.chats.create({ model: "gemini-3.1-flash-image-preview", config: { responseModalities: ["TEXT", "IMAGE"] },});// First turn: generateconst response1 = await chat.sendMessage( "Create a vibrant infographic explaining photosynthesis as a recipe, styled like a colorful kids cookbook");const imageParts1 = response1.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true,);const finalImagePart1 = imageParts1.at(-1);if (finalImagePart1) { fs.writeFileSync("photosynthesis.png", Buffer.from(finalImagePart1.inlineData.data, "base64"));}// Second turn: refineconst response2 = await chat.sendMessage( "Update this infographic to be in Spanish. Do not change any other elements.");const imageParts2 = response2.candidates[0].content.parts.filter( (part) => part.inlineData && part.thought !== true,);const finalImagePart2 = imageParts2.at(-1);if (finalImagePart2) { fs.writeFileSync("photosynthesis_spanish.png", Buffer.from(finalImagePart2.inlineData.data, "base64"));}