中文(繁體)

目前位置: 首頁> Gemini 教學> 如何使用Gemini API 生成圖片

如何使用Gemini API 生成圖片

作者: LoRA 時間:

Gemini API 支持使用Gemini 2.0 Flash 實驗版和Imagen 3 生成圖片。

在調用Gemini API 之前,請確保您已安裝所選的SDK,並已配置好Gemini API 密鑰,可以使用。

一、使用Gemini 生成圖片

Gemini 2.0 Flash Experimental 支持輸出文本和內嵌圖片。這樣,您就可以使用Gemini 以對話方式編輯圖片,或生成包含交織文本的輸出內容(例如,在一次對話中生成包含文本和圖片的博文)。所有生成的圖片都包含SynthID 水印,Google AI 工作室中的圖片也包含可見水印。

注意: 請務必在生成配置中添加responseModalities: ["TEXT", "IMAGE"],以便使用gemini-2.0-flash-exp-image-generation 生成文本和圖片輸出。不允許僅包含圖片。

以下示例展示瞭如何使用Gemini 2.0 生成文本和圖片輸出:

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-exp-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({ apiKey: "GEMINI_API_KEY" });
 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-exp-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();

REST

 curl -s -X POST 
 "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp-image-generation:generateContent?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 

download (1).jpeg

AI 生成的奇幻飛豬圖片

根據提示和上下文,Gemini 將以不同的模式(文本轉圖片、文本轉圖片和文本等)生成內容。下面是一些示例:

1.文本轉圖片

示例提示:“生成一張背景為煙花的埃菲爾鐵塔圖片。”

2.文本轉圖片和文本(交織)

示例提示:“生成帶插圖的西班牙海鮮飯食譜。”

3.圖片和文本轉圖片和文本(交織)

問題示例:(顯示家具擺設的房間圖片)“我的空間適合哪些其他顏色的沙發?您能更新一下圖片嗎?”

4.圖片編輯(文字和圖片轉圖片)

示例提示:“將此圖片編輯成卡通圖片”

示例提示:[貓的圖片] + [枕頭的圖片] +“在這個枕頭上用十字繡製作我貓的圖案。”

5.多輪圖片編輯(聊天)

示例提示:[上傳一張藍色汽車的圖片。 ]“將這輛車改裝成敞篷車。”“現在將顏色更改為黃色。”

二、使用Gemini 編輯圖片

如需執行圖片編輯,請添加圖片作為輸入。以下示例演示瞭如何上傳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-exp-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({ apiKey: "GEMINI_API_KEY" });
 // 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-exp-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();

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-exp-image-generation:generateContent?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

限制

1.為獲得最佳效果,請使用以下語言:英語、西班牙語(墨西哥)、日語、簡體中文、印地語。

2.圖片生成功能不支持音頻或視頻輸入。

3.圖片生成功能未必總會觸發以下操作:

模型可能只會輸出文本。嘗試明確要求獲取圖片輸出(例如“生成圖片”“隨時提供圖片”“更新圖片”)。

模型可能會在中途停止生成。請重試或嘗試使用其他提示。

4.為圖片生成文本時,如果您先生成文本,然後再請求包含文本的圖片,Gemini 的效果會最好。

選擇模型

您應該使用哪種模型來生成圖片?具體取決於您的使用場景。

Gemini 2.0 最適合生成與上下文相關的圖片、混合文本和圖片、納入世界知識以及推理圖片。您可以使用它在長篇幅文本序列中嵌入準確且與上下文相關的視覺內容。您還可以使用自然語言以對話方式修改圖片,同時在整個對話過程中保持上下文。

如果圖片質量是您的首要考慮因素,那麼Imagen 3 是更好的選擇。 Imagen 3 擅長於寫實、藝術細節和特定藝術風格(例如印象派或動漫)。 Imagen 3 還非常適合執行專門的圖片編輯任務,例如更新商品背景、放大圖片以及為視覺內容注入品牌和風格。您可以使用Imagen 3 製作徽標或其他品牌產品設計。

三、使用Imagen 3 生成圖片

Gemini API 提供對Imagen 3 的訪問權限,該模型是Google 質量最高的文本轉圖像模型,具有許多新功能和改進功能。 Imagen 3 可以執行以下操作:

1.與之前的模型相比,生成的圖片細節更豐富、光線更豐富,干擾性偽影更少

2.理解用自然語言編寫的提示

3.生成各種格式和風格的圖片

4.比之前的模型更有效地渲染文本

注意: Imagen 3 僅適用於付費層級,並且始終包含SynthID 水印。

Python

 from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
client = genai.Client(api_key='GEMINI_API_KEY')
response = client.models.generate_images(
   model='imagen-3.0-generate-002',
   prompt='Robot holding a red skateboard',
   config=types.GenerateImagesConfig(
       number_of_images= 4,
   )
)
for generated_image in response.generated_images:
 image = Image.open(BytesIO(generated_image.image.image_bytes))
 image.show()

JavaScript

 import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
async function main() {
 const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
 const response = await ai.models.generateImages({
   model: 'imagen-3.0-generate-002',
   prompt: 'Robot holding a red skateboard',
   config: {
     numberOfImages: 4,
   },
 });
 let idx = 1;
 for (const generatedImage of response.generatedImages) {
   let imgBytes = generatedImage.image.imageBytes;
   const buffer = Buffer.from(imgBytes, "base64");
   fs.writeFileSync(`imagen-${idx}.png`, buffer);
   idx++;
 }
}
main();

REST

 curl -X POST 
   "https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-002:predict?key=GEMINI_API_KEY" 
   -H "Content-Type: application/json" 
   -d '{
       "instances": [
         {
           "prompt": "Robot holding a red skateboard"
         }
       ],
       "parameters": {
         "sampleCount": 4
       }
     }' 

download.jpeg

AI 生成的圖片:廚房裡有兩隻毛茸茸的兔子

Imagen 模型參數

Imagen 目前僅支持英語提示,以及以下參數:

(命名慣例因編程語言而異。)

1.numberOfImages:要生成的圖片數量,介於1 到4(包括這兩個數值)之間。默認值為4。

2.aspectRatio:更改生成圖片的寬高比。支持的值包括"1:1"、"3:4"、"4:3"、"9:16" 和"16:9"。默認值為"1:1"。

3.personGeneration:允許模型生成人物圖片。支持以下值:

"DONT_ALLOW":禁止生成人物圖片。

"ALLOW_ADULT":生成成人圖像,但不生成兒童圖像。 這是默認值。