用第三方聚合平台生图,每张 0.02-0.05 美元,批量生成时成本可观。某次发现这些平台的底层模型就是 Google 的 Imagen/Gemini——那为什么不直接调原生 API?
| 方式 | 每张价格 | 每日 1000 张 |
|------|---------|-------------|
| 第三方聚合平台 | $0.02-0.05 | $20-50 |
| Gemini 原生 API(免费额度)| $0 | $0 |
免费额度数据(2026-03):gemini-2.0-flash-exp 图片生成,每分钟 10 次,每天约 1500 次。超出后按 $0.0015/张 计费,远低于聚合平台。
import os
import base64
from google import genai
from google.genai import types
from PIL import Image
import io
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
def generate_image(prompt: str, output_path: str):
response = client.models.generate_content(
model="gemini-2.0-flash-exp",
contents=prompt,
config=types.GenerateContentConfig(
response_modalities=["IMAGE", "TEXT"]
)
)
for part in response.candidates[0].content.parts:
if part.inline_data and part.inline_data.mime_type.startswith("image/"):
img_bytes = base64.b64decode(part.inline_data.data)
with open(output_path, "wb") as f:
f.write(img_bytes)
print(f"✅ 已保存到 {output_path}")
return
print("❌ 未找到图片内容")
generate_image("一只穿拖鞋的红龙虾,Q版插画风格", "/tmp/lobster.png")
1. 返回 RGB,无透明通道
生成的图片是 RGB 格式,背景通常是白色或彩色,没有透明度(alpha 通道)。如果需要去白底:
from PIL import Image
import numpy as np
def remove_white_bg(input_path: str, output_path: str, threshold=240):
img = Image.open(input_path).convert("RGBA")
data = np.array(img)
# 白色像素设为透明
white_mask = (data[:,:,0] > threshold) & (data[:,:,1] > threshold) & (data[:,:,2] > threshold)
data[:,:,3] = np.where(white_mask, 0, 255)
Image.fromarray(data).save(output_path)
2. 模型选择
gemini-2.0-flash-exp:速度快,免费额度最多,日常够用imagen-3.0-generate-001:质量更高,但需要付费($0.04/张)gemini-2.5-pro:文字+图片理解能力强,适合图生图export GEMINI_API_KEY="your-api-key-here"
# 或写入 ~/.bashrc / .env
API Key 在 [Google AI Studio](https://aistudio.google.com) 免费申请,不需要绑定信用卡就能用免费额度。
能用原生 API 的场景,没理由付钱给聚合平台。15 行代码,成本降到零。