获取 Key 与确认模型
在 Google AI Studio 创建 Gemini API Key,并核对项目计费与模型可用性。创建 Key 不代表图片生成免费。密钥应保留在服务端环境变量中。 官方 Key 指南 ↗
- Nano Banana 2:
gemini-3.1-flash-image - Nano Banana Pro:
gemini-3-pro-image - Nano Banana 2.1:
gemini-nano-banana-2.1 - Nano Banana Lite:
gemini-3.1-flash-lite-image
Gemini 使用 https://generativelanguage.googleapis.com 与 /v1beta/models/{model}:generateContent 路径。渠道 base URL 和别名以各自文档为准。本站模型测试只支持 OpenAI 兼容的同步接口;ImgAPI 可使用 OpenAI 兼容接口,原生 Gemini 使用下方官方 SDK。
渠道示例:接入 ImgAPI
使用 Node.js 18+,在服务端设置环境变量 IMGAPI_CARD_KEY。示例生成一张 Nano Banana 2 图片;使用 Nano Banana Pro 时,将 model 改为 nano-banana-pro。
| 配置项 | 填写内容 |
|---|---|
| Base URL | https://imgapi.vip/prod-api/v1 |
| 鉴权 | Authorization: Bearer $IMGAPI_CARD_KEY |
| Nano Banana 2 | nano-banana-2 |
| Nano Banana Pro | nano-banana-pro |
curl --fail-with-body --max-time 300 \
'https://imgapi.vip/prod-api/v1/images/generations' \
-H "Authorization: Bearer $IMGAPI_CARD_KEY" \
-H 'Content-Type: application/json' \
--data '{
"model": "nano-banana-2",
"prompt": "A flower shop after rain.",
"size": "1024x1024",
"quality": "auto",
"n": 1,
"response_format": "url"
}'此请求按 ImgAPI 规则扣费。密钥仅放在服务端;超时后先核对原任务状态,不要自动重复提交。 ImgAPI 接入文档
官方 Gemini SDK 示例
安装 @google/genai。在服务端配置 GEMINI_API_KEY,切换模型时明确修改 GEMINI_IMAGE_MODEL。此示例使用 Gemini generateContent 协议。
import { GoogleGenAI } from '@google/genai';
import { writeFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
const key = process.env.GEMINI_API_KEY;
if (!key) throw new Error('Set GEMINI_API_KEY on the server');
const ai = new GoogleGenAI({ apiKey: key });
const response = await ai.models.generateContent({
model: process.env.GEMINI_IMAGE_MODEL || 'gemini-3.1-flash-image',
contents: 'Generate an image of a flower shop after rain.'
});
async function saveGeminiImages(response, writeImage, prefix) {
const extensions = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' };
const images = (response.candidates || []).flatMap(candidate => candidate.content?.parts || [])
.map(part => part.inlineData).filter(Boolean);
if (!images.length) throw new Error('No image returned');
for (const [index, image] of images.entries()) {
const ext = extensions[image.mimeType];
if (!ext) throw new Error('Unsupported image format: ' + image.mimeType);
if (typeof image.data !== 'string' || !image.data) throw new Error('Empty image data');
const bytes = Buffer.from(image.data, 'base64');
if (!bytes.length) throw new Error('Empty image data');
await writeImage(prefix + '-' + (index + 1) + '.' + ext, bytes, { flag: 'wx' });
}
}
await saveGeminiImages(response, writeFile, 'result-' + randomUUID());官方生图 SDK 文档 ↗重试前排查错误
401 检查密钥与鉴权格式;403 检查权限与地区可用性;404 检查模型别名与 endpoint;429 检查额度与请求限制。超时可能发生在扣费后,重复提交前应查询任务状态。
指南修订:2026-10-10
