이미지 생성
이미지 생성 (Image generation)
API를 사용하면 텍스트 프롬프트로 gpt-image-2.5-sunburst와 gpt-image-2.5-flare를 통해 이미지를 생성하고 편집할 수 있어요. 편집 정밀도가 가장 중요한 워크플로에는 Sunburst, 빠르고 고품질의 일상적 이미지 생성에는 Flare를 선택하세요. 이미지 생성 기능은 두 가지 API로 접근할 수 있어요.
출처: 문서
본문
Image API
Image API는 각각 다른 기능을 가진 두 엔드포인트를 제공해요.
- Generations: 텍스트 프롬프트를 기반으로 이미지를 처음부터 생성
- Edits: 새 프롬프트로 기존 이미지 수정 (부분적 또는 전체적으로)
Responses API
Responses API는 대화나 다단계 흐름의 일부로 이미지를 생성하게 해요. 이미지 생성을 내장 도구로 지원하고, 컨텍스트 안에서 이미지 입력·출력을 받아요.
Image API에 비해 추가된 것:
- 다중 턴 편집: 프롬프팅으로 이미지에 반복적으로 고충실도 편집 수행
- 유연한 입력: 바이트뿐 아니라 이미지 File ID를 입력 이미지로 수용
image generation 도구를 호출할 수 있는 주류 모델은 지원 모델을 참고하세요.
올바른 API 선택
- 단일 프롬프트에서 이미지 하나만 생성·편집하면 Image API가 최선이에요.
- GPT Image로 대화형·편집 가능한 이미지 경험을 구축하려면 Responses API를 선택하세요.
Image API에서는 model을 gpt-image-2.5-sunburst나 gpt-image-2.5-flare로 직접 설정하세요. Responses API에서는 상위 수준에서 지원되는 주류 모델을 선택하고 image generation 도구의 model 필드에 gpt-image-2.5-sunburst나 gpt-image-2.5-flare를 지정하세요.
두 API 모두 품질, 크기, 형식, 압축을 조정해 출력을 사용자 지정할 수 있게 해요.
이 모델들을 책임감 있게 사용하기 위해, GPT Image 모델을 사용하기 전에 개발자 콘솔에서 API Organization Verification을 완료해야 할 수 있어요.
이미지 생성
이미지 생성 엔드포인트로 텍스트 프롬프트에 기반한 이미지를 만들거나, Responses API의 image generation 도구로 대화의 일부로 생성할 수 있어요.
출력 사용자 지정(크기, 품질, 형식, 압축)에 대해선 아래 출력 사용자 지정 섹션을 참고하세요.
n 파라미터를 설정하면 단일 요청에서 여러 이미지를 한 번에 생성할 수 있어요(기본적으로 API는 이미지 하나를 반환해요).
Image API — 이미지 생성:
from openai import OpenAI
import base64
client = OpenAI()
prompt = """
A children's book drawing of a veterinarian using a stethoscope to
listen to the heartbeat of a baby otter.
"""
result = client.images.generate(model="gpt-image-2.5-sunburst", prompt=prompt)
image_base64 = result.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
# Save the image to a file
with open("otter.png", "wb") as f:
f.write(image_bytes)
(JavaScript, Go, Java, C#, Ruby, curl, CLI 예시도 images.generate를 호출하고 b64_json을 디코드해 파일로 저장하는 같은 패턴입니다.)
Responses API — 이미지 생성:
from openai import OpenAI
import base64
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
# Save the image to a file
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
(JavaScript, Go, Java, C#, Ruby 예시도 image_generation 도구를 쓰고 image_generation_call 출력의 결과를 파일로 저장하는 같은 패턴입니다.)
다중 턴 이미지 생성
Responses API로 이미지 생성 호출 출력을 컨텍스트 안에 제공하거나(이미지 ID만 써도 됨) previous_response_id 파라미터를 사용해 이미지 생성이 포함된 다중 턴 대화를 구축할 수 있어요. 이를 통해 여러 턴에 걸쳐 이미지를 반복하고, 프롬프트를 다듬고, 새 지시를 적용하며, 대화가 진행되면서 시각적 출력을 진화시킬 수 있어요.
Responses API image generation 도구에서 지원 모델은 새 이미지를 생성할지 대화의 기존 이미지를 편집할지 선택할 수 있어요. 선택적 action 파라미터가 이 동작을 제어해요. action: "auto"로 두면 모델이 결정하게 하고, action: "generate"로 설정하면 항상 새 이미지를 만들며, action: "edit"로 설정하면 이미지가 컨텍스트에 있을 때 편집을 강제해요.
action으로 이미지 생성 강제:
from openai import OpenAI
import base64
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[
{"type": "image_generation", "model": "gpt-image-2.5-sunburst", "action": "generate"}
],
)
# Save the image to a file
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
컨텍스트에 이미지를 제공하지 않고 edit를 강제하면 호출이 오류를 반환해요. 모델이 생성·편집 시점을 결정하게 하려면 action을 auto로 두세요.
previous_response_id 사용 — 다중 턴 이미지 생성:
from openai import OpenAI
import base64
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_data = [
output.result
for output in response.output
if output.type == "image_generation_call"
]
if image_data:
image_base64 = image_data[0]
with open("cat_and_otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
# Follow up
response_fwup = client.responses.create(
model="gpt-6-astra",
previous_response_id=response.id,
input="Now make it look realistic",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_data_fwup = [
output.result
for output in response_fwup.output
if output.type == "image_generation_call"
]
if image_data_fwup:
image_base64 = image_data_fwup[0]
with open("cat_and_otter_realistic.png", "wb") as f:
f.write(base64.b64decode(image_base64))
이미지 ID 사용 — 다중 턴 이미지 생성:
import openai
import base64
response = openai.responses.create(
model="gpt-6-astra",
input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_generation_calls = [
output for output in response.output if output.type == "image_generation_call"
]
image_data = [output.result for output in image_generation_calls]
if image_data:
image_base64 = image_data[0]
with open("cat_and_otter.png", "wb") as f:
f.write(base64.b64decode(image_base64))
# Follow up
response_fwup = openai.responses.create(
model="gpt-6-astra",
input=[
{
"role": "user",
"content": [{"type": "input_text", "text": "Now make it look realistic"}],
},
{
"type": "image_generation_call",
"id": image_generation_calls[0].id,
},
],
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_data_fwup = [
output.result
for output in response_fwup.output
if output.type == "image_generation_call"
]
if image_data_fwup:
image_base64 = image_data_fwup[0]
with open("cat_and_otter_realistic.png", "wb") as f:
f.write(base64.b64decode(image_base64))
결과: "Generate an image of gray tabby cat hugging an otter with an orange scarf" → 고양이와 수달 이미지, "Now make it look realistic" → 사실적인 버전. (각 언어 예시의 전체 코드는 원문을 참고하세요.)
스트리밍
Responses API와 Image API는 스트리밍 이미지 생성을 지원해요. API가 생성하면서 부분 이미지를 스트리밍할 수 있어 더 인터랙티브한 경험을 제공해요.
partial_images 파라미터를 조정해 0-3개의 부분 이미지를 받을 수 있어요.
partial_images를 0으로 설정하면 최종 이미지만 받아요.- 0보다 큰 값에서는 전체 이미지가 더 빨리 생성되면 요청한 수의 부분 이미지를 모두 받지 못할 수 있어요.
Responses API — 이미지 스트리밍:
from openai import OpenAI
import base64
client = OpenAI()
def save_base64_image(filename, image_base64):
image_bytes = base64.b64decode(image_base64)
with open(filename, "wb") as f:
f.write(image_bytes)
stream = client.responses.create(
model="gpt-6-astra",
input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
stream=True,
tools=[
{"type": "image_generation", "model": "gpt-image-2.5-sunburst", "partial_images": 2}
],
)
for event in stream:
if event.type == "response.image_generation_call.partial_image":
idx = event.partial_image_index
save_base64_image(f"river-partial-{idx}.png", event.partial_image_b64)
elif event.type == "response.completed":
image_data = [
output.result
for output in event.response.output
if output.type == "image_generation_call"
]
if image_data:
save_base64_image("river-final.png", image_data[0])
(JavaScript, Go, Java, Ruby 예시도 partial_image 이벤트와 completed 이벤트를 처리해 부분·최종 이미지를 저장하는 같은 패턴입니다.)
Image API — 이미지 스트리밍:
from openai import OpenAI
import base64
client = OpenAI()
stream = client.images.generate(
prompt="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
model="gpt-image-2.5-sunburst",
stream=True,
partial_images=2,
)
for event in stream:
if event.type == "image_generation.partial_image":
idx = event.partial_image_index
image_base64 = event.b64_json
image_bytes = base64.b64decode(image_base64)
with open(f"river{idx}.png", "wb") as f:
f.write(image_bytes)
결과: Partial 1, Partial 2, 최종 이미지. 프롬프트: 흰 올빼미 깃털로 만든 강, 고요한 겨울 풍경을 감싸며 흐르는 이미지.
개정된 프롬프트
Responses API에서 image generation 도구를 쓸 때 주류 모델(예: gpt-5.5)이 성능 향상을 위해 프롬프트를 자동으로 개정해요.
개정된 프롬프트는 image generation call의 revised_prompt 필드에서 접근할 수 있어요.
{
"id": "ig_123",
"type": "image_generation_call",
"status": "completed",
"revised_prompt": "A gray tabby cat hugging an otter. The otter is wearing an orange scarf. Both animals are cute and friendly, depicted in a warm, heartwarming style.",
"result": "..."
}
이미지 편집
image edits 엔드포인트로 할 수 있는 것:
- 기존 이미지 편집
- 다른 이미지를 참조로 사용해 새 이미지 생성
- 이미지와 교체할 영역을 식별하는 마스크를 업로드해 이미지 일부 편집
이미지 참조로 새 이미지 생성
하나 이상의 이미지를 참조로 사용해 새 이미지를 생성할 수 있어요.
이 예시에서는 4개의 입력 이미지를 사용해 참조 이미지의 항목을 담은 선물 바구니 새 이미지를 생성할게요.
Responses API로 입력 이미지를 3가지 방법으로 제공할 수 있어요.
- 완전한 URL 제공
- Base64 인코딩 data URL로 이미지 제공
- 파일 ID 제공(Files API로 생성)
파일 생성, base64 이미지 생성, 이미지 편집:
from openai import OpenAI
import base64
client = OpenAI()
def encode_image(file_path):
with open(file_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
def create_file(file_path):
with open(file_path, "rb") as file_content:
result = client.files.create(file=file_content, purpose="vision")
return result.id
prompt = """Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures."""
base64_image1 = encode_image("body-lotion.png")
base64_image2 = encode_image("soap.png")
file_id1 = create_file("bath-bomb.png")
file_id2 = create_file("incense-kit.png")
response = client.responses.create(
model="gpt-6-astra",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{
"type": "input_image",
"image_url": f"data:image/png;base64,{base64_image1}",
},
{
"type": "input_image",
"image_url": f"data:image/png;base64,{base64_image2}",
},
{
"type": "input_image",
"file_id": file_id1,
},
{
"type": "input_image",
"file_id": file_id2,
},
],
}
],
tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)
image_generation_calls = [
output for output in response.output if output.type == "image_generation_call"
]
image_data = [output.result for output in image_generation_calls]
if image_data:
image_base64 = image_data[0]
with open("gift-basket.png", "wb") as f:
f.write(base64.b64decode(image_base64))
else:
print(response.output_text)
(JavaScript, Go, Java, C#, Ruby 예시도 input_image 항목으로 base64·file ID 이미지를 제공하고 image_generation 도구로 편집하는 같은 패턴입니다.)
(이 가이드 뒤쪽에는 출력 사용자 지정: 품질/크기/형식/압축, 지원 모델, 비용 계산 등의 섹션이 이어집니다.)
더 알아보기 (Learn more)
관련 문서: 이미지와 비전, 이미지 프롬프팅, 이미지 입력 비용 계산기 가이드를 함께 보면 좋아요.