Skip to content
,

OpenAI Image API Tutorial in Python: GPT-Image-2.6 Guide

12–18 minutes
Woman in a bright co-working space with plants holding a tablet with an IMAGE API card, hook $0.04 per image gpt-image-2.6 API

OpenAI’s image API now runs on the GPT-Image-2.6 family, released on 4 November 2026 as two models: Sunburst for detail and Flare for speed. This tutorial shows you how to call both from Python, step by step.

You will generate images, edit photos, make transparent PNGs and use the image tool inside the Responses API. We also cover real per-image prices, limits and the errors you are most likely to hit.

TLDR

  • Current models: gpt-image-2.6-sunburst (detail, consistent edits) and gpt-image-2.6-flare (fast iteration).
  • Endpoints: client.images.generate(), client.images.edit(), or the image_generation tool in client.responses.create().
  • Price: $30 per 1M image output tokens. A 1024×1024 image costs about $0.025 (low) to $0.21 (max) in output tokens.
  • Transparent backgrounds: background="transparent" with PNG or WebP output.
  • Batch API: half price ($15 per 1M image output tokens).
  • Old models: gpt-image-1 shut down on 23 October 2026; DALL-E 2 and 3 retired on 12 May 2026.

What the OpenAI Image API Is (and When to Use It)

The OpenAI Image API turns a text prompt (and optional reference images) into a finished image. It returns the image as base64 data, which you decode and save as a file.

There are two ways to reach the same models:

  • Image API: two endpoints, /v1/images/generations (create from scratch) and /v1/images/edits (change existing images). Best for one prompt, one image.
  • Responses API: a chat model such as gpt-6.2-astra calls a built-in image_generation tool. Best for multi-turn editing, chat apps and agents.

OpenAI’s own advice is simple. If you only need to generate or edit a single image from one prompt, use the Image API. If you want a conversational, editable image experience, use the Responses API.

Typical uses include product shots, blog thumbnails, ad variations, icons, logos as SVG, stickers with transparent backgrounds and short animated GIFs.

Current GPT Image Models in December 2026

Model names change fast here, so this table is taken from the OpenAI API reference and model pages as of 3 December 2026.

Model ID Status Best for
gpt-image-2.6-sunburst Latest (4 Nov 2026) Detailed compositions, consistent multi-step edits. Default model on the edit endpoint.
gpt-image-2.6-flare Latest (4 Nov 2026) Fast drafts, posters, product layouts. As little as about 6 seconds at low quality (OpenAI).
gpt-image-2.5-sunburst / gpt-image-2.5-flare Available (snapshots dated 2026-09-08) Same prices as 2.6; still used in many doc examples.
gpt-image-2 Available (snapshot 2026-04-21) Older; quality only up to high.
gpt-image-1.5, gpt-image-1-mini, chatgpt-image-latest Available Legacy integrations.
gpt-image-1 Shut down 23 Oct 2026 Migrate to a 2.5 or 2.6 model.
dall-e-2, dall-e-3 Retired 12 May 2026 Migrate.

Both 2.6 models take text and image input, output images, and cost exactly the same. The difference is tuning: Flare is built for speed, while Sunburst keeps faces and products steadier across edits.

OpenAI GPT-Image-2.6 Sunburst model page showing model ID gpt-image-2.6-sunburst, $30 per 1M image output tokens, text and image input
Official OpenAI GPT-Image-2.6 Sunburst model page (checked 3 Dec 2026).

Tip: Iterate on gpt-image-2.6-flare at quality="low", then re-run your final prompt on Sunburst at medium or high. For the ChatGPT side of this release (GIFs and saved references), see our ChatGPT Images 2.6 guide.

Prerequisites and Setup

You need three things before the first call:

  • An OpenAI API account with credit: the image API is pay as you go. There is no free image quota.
  • An API key: follow our OpenAI API key guide if you do not have one yet.
  • Python 3.9 or newer and the official openai package. We checked the code against version 3.62.2 (released 2 December 2026).
  1. Verify your organization if asked. OpenAI says you may need to complete API Organization Verification in the developer console before you can use GPT Image models.
  2. Create a project folder and a virtual environment. Run python -m venv .venv, then activate it (source .venv/bin/activate on macOS/Linux or .venv\Scripts\activate on Windows).
  3. Install or upgrade the SDK. Run pip install -U openai. Older SDKs may reject new values like xhigh or gif.
  4. Set your key as an environment variable. On macOS/Linux run export OPENAI_API_KEY="sk-..."; on Windows PowerShell run $env:OPENAI_API_KEY="sk-...". The SDK reads it automatically.
  5. Run a test script. Save Example 1 below as generate.py and run python generate.py. A PNG should appear in the folder.

Warning: Never paste your key into code you commit or share. Keep it in the environment or a .env file listed in .gitignore.

New to the SDK in general? Our OpenAI API Python tutorial covers text, streaming and the client basics.

Example 1: Generate an Image

This is the smallest useful script. It asks Flare for a portrait poster at low quality and saves it as a PNG.

import base64
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY

result = client.images.generate(
    model="gpt-image-2.6-flare",
    prompt="Flat vector poster for a coffee shop called 'Bean There', warm colours, big clear title",
    size="1024x1536",      # portrait
    quality="low",         # low, medium, high, xhigh, max, auto
    n=1,
)

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

print("Saved poster.png")
print("Usage:", result.usage)

A few things to know about the response:

  • data[0].b64_json: GPT image models always return base64. The old response_format="url" option is not supported.
  • usage: shows input_tokens, output_tokens and a split into text and image input tokens. Log it to track real cost.
  • No revised_prompt: the Image API does not return one for GPT image models (the Responses tool does).
  • No style: the old DALL-E vivid/natural setting is not supported. Describe the style in the prompt.

Control planning with complexity

GPT-Image-2.6 adds a complexity field: low, medium or high. It sets how much the model plans before drawing, separately from quality.

If you leave it out, both models use high. OpenAI suggests lower complexity for focused edits and higher for dense text and busy layouts, and there is no extra fee for changing it.

result = client.images.generate(
    model="gpt-image-2.6-sunburst",
    prompt="Infographic with 6 labelled steps for brewing pour-over coffee",
    size="1536x1024",
    quality="medium",
    complexity="high",
)

Example 2: Transparent Background PNG

For logos, stickers and product cut-outs, set background="transparent". Transparency needs PNG or WebP output; JPEG has no alpha channel.

import base64
from openai import OpenAI

client = OpenAI()

result = client.images.generate(
    model="gpt-image-2.6-sunburst",
    prompt="A cute cartoon cactus sticker with a thick white outline, no background",
    size="1024x1024",
    quality="medium",
    background="transparent",   # transparent, opaque or auto
    output_format="webp",       # png or webp for transparency
    output_compression=80,      # 0-100, only for webp and jpeg
)

with open("cactus.webp", "wb") as f:
    f.write(base64.b64decode(result.data[0].b64_json))

WebP at 80 gives a much smaller file than PNG, which helps if you serve the image on a website. OpenAI also notes that JPEG is faster than PNG, so use JPEG when you do not need transparency and speed matters.

SVG and GIF output

The 2.6 models can also return vector and animated output from the Image API:

  • SVG: set output_format="svg" on the generations endpoint with n=1. No streaming, partial images or compression. The edit endpoint does not output SVG. Decode b64_json and save the XML with a .svg extension.
  • GIF: set output_format="gif" on generations or edits. Use frame_count (2 to 16, default 9) and frame_duration_ms (20 to 2,000 ms, default 200). GIF needs preview access for the model and does not support streaming, masks or custom compression.

Note: SVG and GIF depend on your project having access to those features. If you get an error about access, fall back to PNG for now.

Example 3: Edit Images and Use Masks

The edit endpoint takes one or more images plus a prompt. You can send up to 16 input images to combine items from several references into one scene.

import base64
from openai import OpenAI

client = OpenAI()

result = client.images.edit(
    model="gpt-image-2.6-sunburst",
    image=[
        open("bath-bomb.png", "rb"),
        open("body-lotion.png", "rb"),
        open("soap.png", "rb"),
    ],
    prompt=(
        "Photorealistic gift basket on a white background labelled 'Relax and Unwind', "
        "with a ribbon, containing all the items in the reference pictures."
    ),
    quality="medium",
    complexity="low",   # OpenAI recommends low for most quick edits
)

with open("basket.png", "wb") as f:
    f.write(base64.b64decode(result.data[0].b64_json))

Edit only part of an image with a mask

A mask tells the model which area to change. Transparent pixels in the mask mark the area to edit.

result = client.images.edit(
    model="gpt-image-2.6-sunburst",
    image=open("sunlit_lounge.png", "rb"),
    mask=open("mask.png", "rb"),
    prompt="A sunlit indoor lounge area with a pool containing a flamingo",
)

with open("composition.png", "wb") as f:
    f.write(base64.b64decode(result.data[0].b64_json))

Mask rules from the OpenAI guide:

  • Same format and size: the image and mask must match, and each must be under 50 MB.
  • Alpha channel required: a plain black-and-white mask fails until you add an alpha channel (for example with Pillow or FFmpeg).
  • Prompt-based: the model may not follow the exact mask shape. With several images, the mask applies to the first one.

The 2.6 models also support markup: a transparent PNG overlay where you circle or draw on the area to change. It must match the first image’s size, can be up to 16,777,216 pixels and 50 MB, and cannot be combined with a mask.

Example 4: The Image Tool in the Responses API

In the Responses API you pick a mainline model at the top level and add the image_generation tool. The tool’s model field chooses the image model.

import base64
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6.2-astra",
    input="Generate an image of a grey tabby cat hugging an otter with an orange scarf",
    tools=[{
        "type": "image_generation",
        "model": "gpt-image-2.6-sunburst",
        "quality": "medium",
        "size": "1024x1024",
    }],
)

images = [o for o in response.output if o.type == "image_generation_call"]
if images:
    with open("cat_otter.png", "wb") as f:
        f.write(base64.b64decode(images[0].result))
    print("Revised prompt:", images[0].revised_prompt)

# Follow-up edit in the same thread
follow_up = client.responses.create(
    model="gpt-6.2-astra",
    previous_response_id=response.id,
    input="Now make it look like a watercolour painting",
    tools=[{"type": "image_generation", "model": "gpt-image-2.6-sunburst"}],
)

Useful tool options:

  • action: auto (default, the model decides), generate or edit. Forcing edit with no image in context returns an error.
  • partial_images: 0 to 3, used with stream=True to show a preview while the image renders. Each partial costs an extra 100 image output tokens.
  • Inputs: images can be a URL, a base64 data URL, or a Files API ID uploaded with purpose="vision".

Note: Responses API calls bill the mainline model’s tokens on top of the image cost. For simple one-shot jobs, the Image API is cheaper.

curl Example

The same generate call from the terminal. It saves the raw JSON, then decodes the image with jq and base64.

curl https://api.openai.com/v1/images/generations \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2.6-flare",
    "prompt": "Minimal line icon of a paper plane, black on transparent",
    "size": "1024x1024",
    "quality": "low",
    "background": "transparent",
    "output_format": "png"
  }' > out.json

jq -r '.data[0].b64_json' out.json | base64 -d > plane.png

On macOS, use base64 -D instead of base64 -d if your version complains.

Sizes, Quality and Other Options

These values come from the Create Image API reference and the image generation guide.

Parameter Values Default
size 1024x1024, 1536x1024, 1024x1536, auto, or custom WIDTHxHEIGHT auto
quality low, medium, high, xhigh, max, auto auto
complexity low, medium, high high
background transparent, opaque, auto auto
output_format png, webp, jpeg, gif, svg png
output_compression 0 to 100 (webp and jpeg only) 100
n 1 to 10 (SVG needs 1) 1
moderation auto, low auto
stream / partial_images true/false; 0 to 3 false; 0
safety_identifier Hashed user ID, max 128 characters none

Custom sizes

Sunburst and Flare accept custom sizes such as 1536x864 (16:9). The rules are strict:

  • Multiples of 16: both width and height.
  • Aspect ratio: between 1:3 and 3:1.
  • Edges: no side over 3,840 pixels.
  • Total pixels: between 655,360 and 8,294,400 (that is 4K, 3840×2160). For GPT-Image-2.5, anything above 2560×1440 is experimental.

Prices per Image with a Worked Example

GPT image models are billed per token, not per picture. Both 2.6 models share the same rates on the OpenAI pricing page:

Token type (per 1M) Standard Batch
Text input $5.00 $2.50
Cached text input $1.25 $0.625
Image input $8.00 $4.00
Cached image input $2.00 $1.00
Image output $30.00 $15.00

To turn that into a price per image, OpenAI’s guide has a calculator. We ran it for the GPT-Image-2.6 models at the three standard sizes:

OpenAI image cost calculator for GPT-Image-2.6 at medium quality 1024x1024 showing 1,449 output tokens and $0.04347 per image
Official OpenAI image generation guide cost calculator (checked 3 Dec 2026).
Quality 1024×1024 tokens 1024×1024 cost 1536×1024 or 1024×1536 tokens Landscape/portrait cost
low 824 $0.0247 664 $0.0199
medium 1,449 $0.0435 1,132 $0.0340
high 1,756 $0.0527 1,372 $0.0412
xhigh 3,122 $0.0937 2,459 $0.0738
max 7,024 $0.2107 5,488 $0.1646

These are output-only estimates. They leave out your prompt’s text tokens, any input images and streaming partials. Oddly, the calculator shows the 1536×1024 sizes using fewer tokens than the square one, so check usage on your own calls.

Worked example: 200 product images

Say you need 200 square product images on Flare at medium quality, each with a 100-token prompt:

  1. Image output: 200 × 1,449 tokens = 289,800 tokens × $30 / 1M = $8.69.
  2. Text input: 200 × 100 tokens = 20,000 tokens × $5 / 1M = $0.10.
  3. Total: about $8.79, or roughly 4.4 cents per image.
  4. Through the Batch API: half of that, about $4.40, if you can wait for results.

Edits add image input tokens at $8 per 1M for every reference image you send. Retries, n above 1 and the Responses API’s chat model tokens also add up.

Tip: For big jobs that do not need instant results, our OpenAI Batch API tutorial shows how to submit them at half price. For every other OpenAI model’s rates, see OpenAI API pricing.

Moderation, Limits and Safety

All prompts and generated images are filtered under OpenAI’s content policy. The moderation parameter controls how strict that filter is:

  • auto (default): standard filtering that limits certain kinds of potentially age-inappropriate content.
  • low: less restrictive filtering. It does not switch the content policy off.
Limit Value
Prompt length 32,000 characters
Images per request (n) 1 to 10
Input images per edit Up to 16
Image and mask file size Under 50 MB each
Markup layer 16,777,216 pixels, 50 MB
Max resolution 3840×2160 (8,294,400 pixels)
GIF frames 2 to 16 frames, 20 to 2,000 ms each
Partial images 0 to 3
Latency Complex prompts can take up to 2 minutes
Rate limits Set by your usage tier; see the Limits page in your organization settings

OpenAI also lists known weak spots: precise text placement, keeping recurring characters consistent across separate generations, and exact layout control.

If your app serves end users, send a safety_identifier with each request. Hash a username or email rather than sending it raw. It replaces the deprecated user parameter.

Troubleshooting: Common Errors and Fixes

OpenAI’s advice is to log the request ID, retry rate-limit and server errors with backoff, and never auto-retry quota errors or image errors that need a changed prompt.

Error What it means Fix
image_generation_user_error with code moderation_blocked The prompt, an input image or the output was blocked. moderation_details.moderation_stage says input, output or unknown. Rewrite the prompt or change the image. Do not retry unchanged. Show users a generic message.
401 “Incorrect API key provided” Key is wrong, revoked or not loaded. Check OPENAI_API_KEY in the same shell, or create a new key.
403 or access errors on GPT Image models Organization not verified, or the region is not supported. Complete API Organization Verification in the console; check the supported countries list.
429 “Rate limit reached for requests” Too many calls for your tier. Wait at least as long as the Retry-After header, then retry with backoff.
429 “Credit balance exhausted” No prepaid credit left. Add credit in billing settings.
429 “Project spend limit reached” Your own spend cap kicked in. Raise or remove the project or organization limit.
400 on size Custom size breaks a rule. Use multiples of 16, ratio 1:3 to 3:1, max 3840 per edge.
400 on background Transparent background with JPEG. Switch to png or webp.
Error when forcing action="edit" No image in the conversation. Send an input image or use auto.
Mask edit fails Mask has no alpha channel or a different size. Save the mask as RGBA at the same size and format.
503 “Model temporarily overloaded” Short-term capacity issue. Honour Retry-After and retry.
AttributeError on data[0].url GPT image models do not return URLs. Read data[0].b64_json and decode it.

For a full list of API status codes, see our OpenAI API errors guide.

Frequently Asked Questions

What is the newest OpenAI image model for the API?

As of December 2026, the newest models are gpt-image-2.6-sunburst and gpt-image-2.6-flare, released on 4 November 2026. Sunburst is for detail and consistent edits, and Flare is for speed.

How much does one image cost with the OpenAI API?

Image output costs $30 per 1M tokens. A 1024×1024 image works out to about $0.025 at low quality, $0.043 at medium, $0.053 at high and $0.21 at max, plus your prompt and any input images.

Is Flare cheaper than Sunburst?

No. Both use the same token prices. OpenAI notes that equal rates do not always mean equal cost, because token use can differ by model and quality, so compare usage on your own prompts.

How do I get a transparent background?

Set background="transparent" and output_format to png or webp. JPEG cannot hold transparency.

Can I still use DALL-E 3 or gpt-image-1?

No. DALL-E 2 and DALL-E 3 were retired on 12 May 2026, and gpt-image-1 shut down on 23 October 2026. Move to a GPT-Image-2.5 or 2.6 model.

Does the image API return a URL?

No. GPT image models always return base64 in b64_json. Decode it and save the bytes, or upload them to your own storage.

Should I use the Image API or the Responses API?

Use the Image API for single generate or edit jobs. Use the Responses API image tool for chat-style, multi-turn editing, but remember you also pay for the chat model’s tokens.

What does moderation=”low” do?

It makes filtering less restrictive than the default auto. OpenAI’s content policy still applies to every prompt and image.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a bright co-working space with plants holding a tablet with an IMAGE API card, hook $0.04 per image gpt-image-2.6 API