from openai import OpenAI
import base64
import os
client = OpenAI(
api_key="AIHUBMIX_API_KEY", # AIHUBMIX 키 "sk-***"로 교체
base_url="https://aihubmix.com/v1"
)
prompt = """영화 [블랙 스완]의 포스터를 재디자인하세요, 3D 만화, 부드러운 렌더링, 밝은 톤, 2:3 세로."""
result = client.images.generate(
model="gpt-image-1",
prompt=prompt,
n=1, # 생성할 이미지 수, 최대 10개
size="1024x1536", # 1024x1024 (정사각형), 1536x1024 (3:2 가로), 1024x1536 (2:3 세로), auto (기본값)
quality="high", # high, medium, low, auto (기본값)
moderation="low", # low, auto (기본값) - 업데이트된 openai 패키지 필요 📍
background="auto", # transparent, opaque, auto (기본값)
)
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}의 이미지 데이터가 비어 있어 저장을 건너뜁니다.")