跳至內容
English
圖像生成

參考圖輸入與編輯 ​

讀取本機圖片,加入編輯指令並保存結果。

多語言 API 呼叫 ​

執行方式見多語言範例說明。先設定 API_KEY,並替換模型、檔案網址及 ID 占位值;四種方式會顯示相同請求的原始回應。

此處顯示 API 原始回應;圖片的 Base64 解碼、下載與保存請接續本頁或圖像概覽的完整流程。 YOUR_IMAGE_BASE64 需替換為 PNG 的完整 Base64(不含 Data URI 前綴);下方 Python 片段示範如何讀取本機檔案。

bash
curl --fail-with-body --silent --show-error --max-time 180 \
  --request POST \
  --url "https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent" \
  --header "x-goog-api-key: $API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Change the background to pale gray. Preserve the product shape and logo."
        },
        {
          "inlineData": {
            "mimeType": "image/png",
            "data": "YOUR_IMAGE_BASE64"
          }
        }
      ]
    }
  ],
  "generationConfig": {
    "responseModalities": [
      "TEXT",
      "IMAGE"
    ]
  }
}'
python
import os
import requests

headers = {
    'x-goog-api-key': os.environ["API_KEY"],
    'Content-Type': 'application/json',
}
payload = {'contents': [{'role': 'user',
               'parts': [{'text': 'Change the background to pale gray. Preserve the '
                                  'product shape and logo.'},
                         {'inlineData': {'mimeType': 'image/png',
                                         'data': 'YOUR_IMAGE_BASE64'}}]}],
 'generationConfig': {'responseModalities': ['TEXT', 'IMAGE']}}
response = requests.request(
    'POST', 'https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent', headers=headers,
    json=payload,
    timeout=180,
)
response.raise_for_status()
print(response.text)
js
if (!process.env.API_KEY) throw new Error("Set API_KEY first.");
const response = await fetch("https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent", {
  method: "POST",
  headers: {
    "x-goog-api-key": process.env.API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "Change the background to pale gray. Preserve the product shape and logo."
        },
        {
          "inlineData": {
            "mimeType": "image/png",
            "data": "YOUR_IMAGE_BASE64"
          }
        }
      ]
    }
  ],
  "generationConfig": {
    "responseModalities": [
      "TEXT",
      "IMAGE"
    ]
  }
}),
  signal: AbortSignal.timeout(180_000),
});
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
console.log(await response.text());
java
import java.net.URI;
import java.net.http.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("API_KEY");
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("Set API_KEY first.");
        }
        String payload = String.join("\n",
            "{",
            "  \"contents\": [",
            "    {",
            "      \"role\": \"user\",",
            "      \"parts\": [",
            "        {",
            "          \"text\": \"Change the background to pale gray. Preserve the product shape and logo.\"",
            "        },",
            "        {",
            "          \"inlineData\": {",
            "            \"mimeType\": \"image/png\",",
            "            \"data\": \"YOUR_IMAGE_BASE64\"",
            "          }",
            "        }",
            "      ]",
            "    }",
            "  ],",
            "  \"generationConfig\": {",
            "    \"responseModalities\": [",
            "      \"TEXT\",",
            "      \"IMAGE\"",
            "    ]",
            "  }",
            "}"
        );
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30)).build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent"))
            .timeout(Duration.ofSeconds(180))
            .header("x-goog-api-key", apiKey)
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString(payload))
            .build();
        HttpResponse<String> response = client.send(
            request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": "
                + response.body());
        }
        System.out.println(response.body());
    }
}

使用本機參考圖 ​

  1. 先執行 Nano Banana 的文字生圖範例,確認路由及金鑰正常。
  2. 將真正的 PNG 圖片存為 reference.png,放在 nano_banana.py 同一目錄。
  3. 將腳本原本的 parts = ... 替換為下方程式,其他程式保留。
  4. 再次執行 python3 nano_banana.py,開啟輸出圖片確認背景已修改、主體細節保留。
python
reference = Path("reference.png")
parts = [
    {"text": "Change the background to pale gray. Preserve the product shape and logo."},
    {"inlineData": {"mimeType": "image/png",
                    "data": base64.b64encode(reference.read_bytes()).decode("ascii")}},
]

多圖與格式 ​

多張參考圖可加入多個 inlineData 區塊,並在文字中說明每張圖片的用途。JPEG 使用 image/jpeg,WebP 使用 image/webp;副檔名更改不會轉換檔案格式。圖片大小與張數請依所選模型限制,先用單張小圖驗證。

若需要的是 OCR、圖片問答或文件摘要,請使用 Messages 檔案分析。圖像生成與圖像理解是不同工作。

排錯 ​

找不到檔案時檢查執行目錄;格式錯誤時核對 MIME 與原始資料;沒有圖片回傳時檢查 Nano Banana 頁面的 promptFeedback 和模型能力。此處使用原生 Gemini 的 inlineData,不要混入舊版 image_urls 欄位。