Skip to main content
Lesson 2 of 12 · Image Generation via API: GPT Image

Create images from a prompt

Lesson 2 of 12 Updated November 2, 2026 Developer
On this page
  1. Create images from a prompt
  2. Anatomy of a generation call
  3. Retrieve the generated image
  4. Generate multiple images in a single call
  5. Write effective prompts
  6. Error handling

Updated November 2, 2026 — Image models. gpt-image-1, the model this course was originally written for, was discontinued on October 23, 2026. gpt-image-1.5, gpt-image-1-mini, and chatgpt-image-latest will be retired on December 1, 2026. Examples now use gpt-image-2.5-sunburst, which offers the highest precision for editing; gpt-image-2.5-flare is faster for standard generation. Both models also support xhigh and max quality settings. GPT Image models always return images in base64: the response_format parameter used by older DALL·E models is not supported and has been removed from the code. Source: Image generation (OpenAI).

Create images from a prompt

The client.images.generate() method is your primary entry point for creating an image from a text description. It relies on just a handful of parameters, but precisely because there are so few, each one counts: the difference between a random result and a predictable one comes down almost entirely to the content of the prompt field. This lesson teaches you to master both.

Anatomy of a generation call

Here is the complete structure of a call with all available parameters.

from openai import OpenAI

client = OpenAI()

response = client.images.generate(
    model="gpt-image-2.5-sunburst",
    prompt="Detailed description of the desired image",
    n=1,
    size="1024x1024",
    quality="high"
)
ParameterTypeDescription
modelstring"gpt-image-2.5-sunburst" (most precise) or "gpt-image-2.5-flare" (fastest)
promptstringImage description (up to 32,000 characters)
nintegerNumber of images to generate (1 to 10)
sizestring"1024x1024", "1024x1536", "1536x1024"
qualitystring"low", "medium", "high"

The 32,000-character limit for the prompt is generous: it allows for highly detailed descriptions, and you will see shortly that detail is your best lever for control.

Retrieve the generated image

The response contains a data object holding the images. GPT Image models always return the image encoded in base64 within the b64_json field: you decode it and write it to disk immediately. The response_format parameter and temporary URLs from older DALL·E models do not apply to GPT Image.

import base64

response = client.images.generate(
    model="gpt-image-2.5-sunburst",
    prompt="A Japanese garden in the rain, photography",
    n=1,
    size="1024x1024",
)

image_data = base64.b64decode(response.data[0].b64_json)

with open("garden.png", "wb") as f:
    f.write(image_data)

print("Image saved: garden.png")

Once the file is written, nothing depends on OpenAI anymore: this is the file you store, serve, or rework.

Generate multiple images in a single call

The n parameter requests multiple variants in a single request. Make this your default reflex when you are exploring a visual direction without knowing which one to keep: four proposals side by side inform you far better than a single one.

import base64
response = client.images.generate(
    model="gpt-image-2.5-sunburst",
    prompt="Minimalist logo for an artisan bakery, white background",
    n=4,
    size="1024x1024",
    quality="high"
)

for i, image in enumerate(response.data):
    with open(f"logo_{i+1}.png", "wb") as f:
        f.write(base64.b64decode(image.b64_json))
    print(f"Variant {i+1}: logo_{i+1}.png")

Watch your costs, however: each image consumes tokens independently, and generating 4 images costs 4 times the price of a single one. Explore with a high n and low quality, reserving high quality for the final selection.

Write effective prompts

The quality of the result depends directly on the precision of your prompt. A good prompt follows a simple structure—subject + style + context + technical details—and the comparison below makes the difference tangible: “a house” leaves the model to invent everything you didn’t say, while the developed version fixes the material, shutter color, time of day, editorial register, and optical treatment.

# Vague prompt — unpredictable result
weak_prompt = "a house"

# Structured prompt — controlled result
strong_prompt = (
    "Provençal country house in blonde stone, "
    "lavender blue shutters, ivy on the facade, "
    "photographed at golden hour, "
    "editorial style for architecture magazine, "
    "centered composition, depth of field"
)

response = client.images.generate(
    model="gpt-image-2.5-sunburst",
    prompt=strong_prompt,
    size="1536x1024",
    quality="high"
)

Declare visual style the same way, by naming a medium rather than hoping for an intention. GPT Image understands a wide variety of registers, and the following loop lets you feel the gap between them on a strictly identical subject: the bicycle in front of the Parisian café changes completely in nature depending on whether you request an editorial photograph, a flat vector illustration, or a pencil sketch.

import base64
styles = [
    "editorial photography, studio lighting",
    "flat design vector illustration",
    "watercolor on textured paper",
    "photorealistic 3D render, Octane Render",
    "pencil sketch on kraft paper",
]

for style in styles:
    prompt = f"A vintage bicycle parked in front of a Parisian café, {style}"
    response = client.images.generate(
        model="gpt-image-2.5-sunburst",
        prompt=prompt,
        size="1024x1024",
        quality="medium"
    )
    filename = f"bicycle_{styles.index(style) + 1}.png"
    with open(filename, "wb") as f:
        f.write(base64.b64decode(response.data[0].b64_json))
    print(f"Style: {style} → {filename}")

Text embedded in the image deserves a separate note, as this is where GPT Image distinguishes itself clearly from its predecessors. Give the message in quotes within the prompt, specify the typeface family and expected graphic treatment, and the rendering will be legible.

response = client.images.generate(
    model="gpt-image-2.5-sunburst",
    prompt=(
        "Promotional poster with the text \"SUMMER SALE -50%\" "
        "in large white letters on a blue-orange gradient background, "
        "modern sans-serif typography, professional commercial style"
    ),
    size="1024x1536",
    quality="high"
)

Error handling

A generation script running in a loop will eventually hit a rate limit or an API error. Handle these two cases distinctly from the start: a RateLimitError calls for a wait and a retry, whereas an APIError requires examining the message before relaunching anything.

import base64
from openai import OpenAI, APIError, RateLimitError

client = OpenAI()

try:
    response = client.images.generate(
        model="gpt-image-2.5-sunburst",
        prompt="A snowy mountain landscape at sunrise",
        size="1024x1024"
    )
    with open("mountain.png", "wb") as f:
        f.write(base64.b64decode(response.data[0].b64_json))

except RateLimitError:
    print("Request limit reached. Wait before retrying.")

except APIError as e:
    print(f"API Error: {e.message}")

To anchor all of this, now write a script that generates three variants of the same subject in three different styles—photo, illustration, watercolor—and saves each image locally in PNG format, using the base64 format for retrieval.