from openai import OpenAI
import base64
import os
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # Replace with your AIHUBMIX 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, # Number of images to generate, maximum 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) - requires updated openai package 📍
background="auto", # transparent, opaque, auto (default)
)
print(result.usage)
# Define file name prefix and save directory
output_dir = "." # You can specify another directory
file_prefix = "image_gen"
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Iterate through all returned image data
for i, image_data in enumerate(result.data):
image_base64 = image_data.b64_json
if image_base64: # Ensure b64_json is not empty
image_bytes = base64.b64decode(image_base64)
# --- Handle filename conflict logic ---
current_index = i
while True:
# Create filename with incremental counter
file_name = f"{file_prefix}_{current_index}.png"
file_path = os.path.join(output_dir, file_name) # Build complete file path
# Check if file exists
if not os.path.exists(file_path):
break # No filename conflict, exit loop
# Filename conflict, increment counter
current_index += 1
# Save image to file using unique file_path
with open(file_path, "wb") as f:
f.write(image_bytes)
print(f"Image saved to: {file_path}")
else:
print(f"Image data for index {i} is empty, skipping save.")