from openai import OpenAI
import base64
import os
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # 換成你在後台生成的 Key "sk-***"
base_url="https://aihubmix.com/v1"
)
prompt = """redesign poster of the movie [Black Swan], 3D cartoon, smooth render, bright tone, 2:3 portrait."""
result = client.images.generate(
model="gpt-image-1",
prompt=prompt,
n=1, # 單次出圖數量,最多 10 張
size="1024x1536", # 1024x1024 (square), 1536x1024 (3:2 landscape), 1024x1536 (2:3 portrait), auto (default)
quality="high", # high, medium, low, auto (default)
moderation="low", # low, auto (default) 需要升級 openai 包 📍
background="auto", # transparent, opaque, auto (default)
)
print(result.usage)
# 定義文件名前綴和保存目錄
output_dir = "." # 可以指定其他目錄
file_prefix = "image_gen"
# 確保輸出目錄存在
os.makedirs(output_dir, exist_ok=True)
# 遍歷所有返回的圖片數據
for i, image_data in enumerate(result.data):
image_base64 = image_data.b64_json
if image_base64: # 確保 b64_json 不為空
image_bytes = base64.b64decode(image_base64)
# --- 文件名衝突處理邏輯開始 ---
current_index = i
while True:
# 構建帶自增序號的文件名
file_name = f"{file_prefix}_{current_index}.png"
file_path = os.path.join(output_dir, file_name) # 構建完整文件路徑
# 檢查文件是否存在
if not os.path.exists(file_path):
break # 文件名不衝突,跳出循環
# 文件名衝突,增加序號
current_index += 1
# 使用找到的唯一 file_path 保存圖片到文件
with open(file_path, "wb") as f:
f.write(image_bytes)
print(f"圖片已保存至:{file_path}")
else:
print(f"第 {i} 張圖片數據為空,跳過保存。")