跳转到主要内容

推荐 endpoint

最小请求

{
  "model": "gemini-2.5-flash-image",
  "contents": [
    {
      "role": "user",
      "parts": [{ "text": "生成一张简洁的 Api.Go 产品海报" }]
    }
  ],
  "generationConfig": {
    "responseModalities": ["TEXT", "IMAGE"]
  }
}

cURL 示例

curl -s "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {
        "parts": [{ "text": "生成一张简洁的 Api.Go 产品海报" }]
      }
    ]
  }'

Python 示例

import base64
import requests

response = requests.post(
    "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent",
    headers={
        "x-goog-api-key": "<GEMINI_API_KEY>",
        "Content-Type": "application/json",
    },
    json={
        "contents": [
            {
                "parts": [{"text": "生成一张简洁的 Api.Go 产品海报"}],
            }
        ]
    },
    timeout=60,
)
response.raise_for_status()

for part in response.json()["candidates"][0]["content"]["parts"]:
    if "inlineData" in part:
        image_bytes = base64.b64decode(part["inlineData"]["data"])
        with open("tidemind-poster.png", "wb") as f:
            f.write(image_bytes)
        print("saved tidemind-poster.png")

Node.js 示例

import { writeFileSync } from "node:fs";

const response = await fetch(
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent",
  {
    method: "POST",
    headers: {
      "x-goog-api-key": process.env.GEMINI_API_KEY,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      contents: [
        {
          parts: [{ text: "生成一张简洁的 Api.Go 产品海报" }]
        }
      ]
    })
  }
);

const data = await response.json();
for (const part of data.candidates[0].content.parts) {
  if (part.inlineData) {
    writeFileSync(
      "tidemind-poster.png",
      Buffer.from(part.inlineData.data, "base64")
    );
    console.log("saved tidemind-poster.png");
  }
}

最佳实践

  • 图片理解和图片生成都走 generateContent,但结果解析方式不同
  • 图片结果通常在 inlineData 中,服务端先解码再落盘
  • 需要复用参考图时,优先用 Files API 而不是每次内联上传