Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/openai/openai-cookbook/llms.txt

Use this file to discover all available pages before exploring further.

OpenAI’s image generation API lets you create high-quality images from text prompts, edit existing images with inpainting, and generate variations from a source image. Two models are available: DALL-E 3, which rewrites your prompts internally for better results and supports style and quality controls; and GPT Image (gpt-image-1), a newer model with stronger instruction-following, photorealism, and world knowledge built in. Both share the same client.images interface.

Generate an image with DALL-E 3

Call client.images.generate with your prompt and preferred settings. DALL-E 3 automatically rewrites short prompts into more detailed descriptions before generation, so you can work at a high level of abstraction.
from openai import OpenAI

client = OpenAI()

response = client.images.generate(
    model="dall-e-3",
    prompt="A futuristic city skyline at sunset, photorealistic",
    size="1024x1024",
    quality="standard",
    n=1
)

image_url = response.data[0].url
print(image_url)
The response includes a URL that is valid for a short window. Download or persist the image if you need it beyond that window.
import requests

image_bytes = requests.get(image_url).content
with open("city.png", "wb") as f:
    f.write(image_bytes)

Sizes, quality, and style

DALL-E 3 exposes three parameters beyond the prompt that have a meaningful effect on output.

Size

DALL-E 3 supports three sizes. The aspect ratio affects composition: square images tend toward balanced scenes, wide images favor landscapes, and tall images suit portraits and mobile-style photography.
SizeAspect ratioBest for
1024x10241:1Icons, product shots, balanced compositions
1792x102416:9Landscapes, banners, wide scenes
1024x17929:16Portraits, mobile wallpapers, vertical compositions

Quality

response = client.images.generate(
    model="dall-e-3",
    prompt="A ceramic coffee mug on a wooden table, studio lighting",
    size="1024x1024",
    quality="hd",   # "standard" or "hd"
    n=1
)
hd quality produces images with finer texture, more consistent composition across the frame, and better adherence to detailed prompts. It adds roughly 10 seconds to generation time and increases cost per image.

Style

response = client.images.generate(
    model="dall-e-3",
    prompt="Logo design of a minimalist mountain range",
    size="1024x1024",
    quality="standard",
    style="natural",   # "vivid" or "natural"
    n=1
)
StyleDescription
vividHyper-real, cinematic, and dramatic. The default in ChatGPT.
naturalCloser to realistic photography or illustration without over-exaggeration. Use when vivid produces results that are too dramatic.
Use natural for logo generation, stock photography, or scenes where realism matters more than cinematic impact. Use vivid when you want bold, striking visuals.

Generate with GPT Image (gpt-image-1)

GPT Image (gpt-image-1) is OpenAI’s newest image generation model. It has broad world knowledge baked in, follows detailed instructions more reliably than previous models, and produces photorealistic results with greater consistency.
import base64
import os
from openai import OpenAI
from PIL import Image
from io import BytesIO

client = OpenAI()

result = client.images.generate(
    model="gpt-image-1",
    prompt=(
        "A product shot of a sleek wireless headphone on a white background, "
        "soft shadows, studio lighting, 4K quality"
    ),
    size="1024x1024"
)

# gpt-image-1 returns base64-encoded image data
image_bytes = base64.b64decode(result.data[0].b64_json)
image = Image.open(BytesIO(image_bytes))
image.save("headphones.png")
gpt-image-1 returns images as base64-encoded JSON (b64_json) rather than URLs. Decode the response before saving or displaying the image.

Detailed instruction following

GPT Image excels at following long, precise specifications. You can describe character design, materials, lighting setup, and compositional rules in a single prompt.
result = client.images.generate(
    model="gpt-image-1",
    prompt=(
        "Render a product packaging box for a premium tea brand. "
        "The box is matte black with gold foil lettering reading 'Aurum Tea'. "
        "A minimalist illustration of a crane in flight appears on the front panel. "
        "Soft ambient lighting from the upper left. No background clutter."
    ),
    size="1024x1024"
)

Edit an image with inpainting

The client.images.edit endpoint lets you modify a specific region of an existing image by providing a mask that identifies the area to change. Only the masked pixels are regenerated; the rest of the image stays intact.
1

Prepare the source image and mask

Both must be PNG files of equal size. The mask uses transparency (alpha channel) to indicate the area to edit — fully transparent pixels will be replaced, opaque pixels will be preserved.
from PIL import Image
import numpy as np

# Open source image
source = Image.open("room.png").convert("RGBA")
width, height = source.size

# Create a mask — make the top-left quarter transparent
mask = Image.new("RGBA", (width, height), (0, 0, 0, 255))
mask_array = np.array(mask)
mask_array[:height // 2, :width // 2, 3] = 0  # transparent region
mask = Image.fromarray(mask_array)

source.save("room_rgba.png")
mask.save("room_mask.png")
2

Send the edit request

with open("room_rgba.png", "rb") as img, open("room_mask.png", "rb") as msk:
    response = client.images.edit(
        model="dall-e-2",
        image=img,
        mask=msk,
        prompt="A large window with a view of a snowy mountain range",
        size="1024x1024",
        n=1
    )

print(response.data[0].url)
The edits endpoint is available for DALL-E 2. DALL-E 3 supports generations only. Check the API reference for the latest model support.

Generate variations

client.images.variations creates alternative versions of an existing image while preserving its general composition and subject matter.
with open("original.png", "rb") as f:
    response = client.images.create_variation(
        model="dall-e-2",
        image=f,
        n=3,
        size="1024x1024"
    )

for i, image in enumerate(response.data):
    print(f"Variation {i + 1}: {image.url}")

Practical use cases

Product photo generation

Generate polished product shots on clean backgrounds at scale, without a photography studio.

Icon and logo prototyping

Rapidly iterate on icon sets and logo concepts before handing off to a designer.

Marketing asset creation

Produce hero images, social banners, and ad creatives from a single descriptive prompt.

Custom avatar generation

Create personalized character designs, avatars, or mascots based on detailed specifications.

Return format options

By default, DALL-E 3 returns a URL. You can request base64-encoded JSON instead if you need to handle the image directly in your application without a separate download step.
response = client.images.generate(
    model="dall-e-3",
    prompt="Abstract geometric art in primary colors",
    size="1024x1024",
    response_format="b64_json"  # or "url"
)

import base64
image_bytes = base64.b64decode(response.data[0].b64_json)
with open("art.png", "wb") as f:
    f.write(image_bytes)

Model comparison

FeatureDALL-E 3GPT Image (gpt-image-1)
Prompt rewritingYes (automatic)No (uses prompt as-is)
PhotorealismHighVery high
Instruction followingGoodExcellent
Output formatURL or b64_jsonb64_json
Edits endpointDALL-E 2 onlyCheck API reference
Style parametervivid / naturalNot applicable
Quality parameterstandard / hdNot applicable

Prompt tips

Getting consistent, high-quality results from image generation models depends heavily on how you write prompts.
  • Be specific about style: “oil painting”, “photorealistic”, “flat vector illustration”, “charcoal sketch”
  • Describe lighting: “soft ambient light”, “dramatic rim lighting”, “golden hour”, “studio lighting with soft shadows”
  • Set the scene: include background, foreground, and compositional intent
  • For DALL-E 3: since prompts are rewritten automatically, you can write naturally; for maximum fidelity to your original intent, add the instruction “I NEED to test how the tool works with extremely simple prompts” to suppress rewriting
  • For GPT Image: prompts are used as-is, so be thorough and precise
# Explicit, detailed prompt for GPT Image
result = client.images.generate(
    model="gpt-image-1",
    prompt=(
        "Overhead flat-lay photograph of a wooden desk with: "
        "an open notebook with handwritten notes in the top left, "
        "a white ceramic mug of black coffee in the top right, "
        "a mechanical keyboard centered at the bottom, "
        "warm afternoon light from the right side, "
        "neutral gray desk surface, shallow depth of field."
    ),
    size="1024x1024"
)

Build docs developers (and LLMs) love