DALL-E 3 API
Overview
DALL-E 3 is OpenAI's image generation model, accessible via the OpenAI Python SDK. It supports text-to-image generation with high prompt fidelity, image editing with alpha-channel masks, and returns a "revised prompt" showing how the model interpreted your request.
Setup
pip install openai python-dotenv
export OPENAI_API_KEY="your_api_key_here"
Core Concepts
- Generations (
/v1/images/generations): Create a new image from a text prompt.
- Edits (
/v1/images/edits): Modify an existing image by painting over a masked region.
- Variations (DALL-E 2 only): Generate variations of an existing image.
- Revised prompt: DALL-E 3 rewrites your prompt for safety and quality — always log
revised_prompt to understand the actual input.
- Response format:
url (temporary CDN link, expires in 1 hour) or b64_json (base64-encoded PNG).
Instructions
Step 1: Initialize the client
import os
import base64
import requests
from pathlib import Path
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
Step 2: Generate an image (text-to-image)
def generate_image(
prompt: str,
model: str = "dall-e-3",
size: str = "1024x1024",
quality: str = "standard",
style: str = "vivid",
output_path: str = "output.png"
) -> dict:
"""
Generate an image with DALL-E 3.
size options: 1024x1024 | 1792x1024 | 1024x1792
quality options: standard | hd
style options: vivid (dramatic) | natural (more realistic)
Returns dict with saved path and revised_prompt.
"""
response = client.images.generate(
model=model,
prompt=prompt,
size=size,
quality=quality,
style=style,
n=1,
response_format="b64_json"
)
image_data = response.data[0]
revised_prompt = image_data.revised_prompt
print(f"Revised prompt: {revised_prompt}")
# Decode and save
img_bytes = base64.b64decode(image_data.b64_json)
Path(output_path).write_bytes(img_bytes)
size_kb = len(img_bytes) // 1024
print(f"Saved: {output_path} ({size_kb} KB)")
return {"path": output_path, "revised_prompt": revised_prompt}
# Standard quality, vivid style
result = generate_image(
prompt="A sleek electric car driving through a futuristic city at night, neon reflections on wet streets, cinematic",
size="1792x1024",
quality="standard",
style="vivid",
output_path="electric_car.png"
)
# HD quality, natural style for photorealism
result = generate_image(
prompt="A professional headshot of a confident businesswoman in a modern office, natural lighting, 50mm lens",
size="1024x1024",
quality="hd",
style="natural",
output_path="headshot.png"
)
Step 3: Image editing with inpainting mask
def edit_image(
image_path: str,
mask_path: str,
prompt: str,
size: str = "1024x1024",
output_path: str = "edited.png"
) -> str:
"""
Edit an image by replacing the masked region with generated content.
image_path: PNG file, RGBA or RGB, must be square, ≤ 4MB
mask_path: PNG file with alpha channel. Transparent pixels = area to edit.
Returns path to the edited image.
"""
with open(image_path, "rb") as img_f, open(mask_path, "rb") as mask_f:
response = client.images.edit(
model="dall-e-2", # edits require dall-e-2
image=img_f,
mask=mask_f,
prompt=prompt,
size=size,
n=1,
response_format="b64_json"
)
img_bytes = base64.b64decode(response.data[0].b64_json)
Path(output_path).write_bytes(img_bytes)
print(f"Edited image saved: {output_path}")
return output_path
# Example: replace the background of a product photo
edit_image(
image_path="product.png", # Original product image
mask_path="background_mask.png", # Alpha mask over background area
prompt="A tropical beach at sunset as background",
size="1024x1024",
output_path="product_beach.png"
)
Step 4: Create a mask programmatically
from PIL import Image # pip install Pillow
import numpy as np
def create_circular_mask(image_path: str, center_x: float = 0.5, center_y: float = 0.5,
radius: float = 0.3, output_path: str = "mask.png") -> str:
"""
Create an inpainting mask with a transparent circle.
center_x/y: 0.0–1.0 relative position
radius: 0.0–0.5 relative radius
"""
img = Image.open(image_path).convert("RGBA")
w, h = img.size
mask = Image.new("RGBA", (w, h), (255, 255, 255, 255)) # fully opaque
cx, cy, r = int(w * center_x), int(h * center_y), int(min(w, h) * radius)
mask_arr = np.array(mask)
Y, X = np.ogrid[:h, :w]
dist = np.sqrt((X - cx)**2 + (Y - cy)**2)
mask_arr[dist <= r, 3] = 0 # transparent = area to edit
Image.fromarray(mask_arr).save(output_path)
print(f"Mask saved: {output_path}")
return output_path
create_circular_mask("product.png", center_x=0.5, center_y=0.5, radius=0.4, output_path="circle_mask.png")
Step 5: Batch generation
import time
def batch_generate(prompts: list[str], size: str = "1024x1024",
quality: str = "standard", output_dir: str = "output/") -> list[str]:
"""Generate multiple images with rate-limit handling."""
Path(output_dir).mkdir(exist_ok=True)
paths = []
for i, prompt in enumerate(prompts):
try:
out_path = f"{output_dir}/image_{i:03d}.png"
result = generate_image(prompt, size=size, quality=quality, output_path=out_path)
paths.append(result["path"])
time.sleep(1) # respect rate limits (5 images/min on standard tier)
except Exception as e:
print(f"Error on prompt {i}: {e}")
time.sleep(5)
return paths
products = [
"A wooden cutting board with fresh vegetables, overhead shot, natural light",
"A ceramic mug with steam rising, cozy kitchen background, warm tones",
"A leather wallet on a marble surface, minimal style, luxury feel"
]
batch_generate(products, quality="hd", output_dir="product_shots")
Parameters reference
| Parameter |
Values |
Description |
model |
dall-e-3, dall-e-2 |
DALL-E 3 = generations only; DALL-E 2 = edits + variations |
size |
1024x1024, 1792x1024, 1024x1792 |
Output dimensions (DALL-E 3) |
quality |
standard, hd |
hd has finer details, costs 2x credits |
style |
vivid, natural |
vivid = dramatic; natural = more realistic |
response_format |
url, b64_json |
URL expires in 1 hour; b64_json is permanent |
n |
1 (DALL-E 3) |
DALL-E 3 supports n=1 only |
DALL-E 3 behaviors to know
- Prompt rewriting: DALL-E 3 automatically rewrites prompts. Log
revised_prompt to understand what was actually generated.
- Safety filters: Some content is refused and returns an error. The revised prompt handles most edge cases automatically.
- No n>1: DALL-E 3 only generates 1 image per API call. Use a loop for batches.
- Edits use DALL-E 2: The
/v1/images/edits endpoint only supports DALL-E 2.
- URL expiry: Response URLs expire after 1 hour. Always download and store images immediately.
Guidelines
- Use
quality="hd" and style="natural" for photorealistic product images.
- Use
quality="standard" and style="vivid" for illustrations, concept art, and marketing visuals.
- For best results, be specific: include subject, style, lighting, camera angle, and mood in the prompt.
- Use
b64_json instead of url format to avoid download failures on slow networks.
- Rate limits: ~5 images/minute on standard tier. Add
time.sleep(1) between batch requests.
- Store API keys in environment variables — never hardcode them.
1---2name: dalle-api3description: >-4 DALL-E 3 API for AI image generation — text-to-image, image editing, and5 variations via OpenAI. Use when generating images from text prompts, creating6 product visuals, illustrating content, or editing images with an inpainting7 mask.8license: Apache-2.09compatibility: "Requires Python 3.9+ or Node.js 18+. Install: pip install openai. OpenAI API key required."10metadata:11 source: https://skillmd.com/skills/eliferjunior/dalle-api12 author: terminal-skills13 version: "1.0.0"14 category: data-ai15 tags: ["dalle", "openai", "image-generation", "text-to-image", "ai-art"]16 use-cases:17 - "Generate product visuals from text descriptions for e-commerce listings"18 - "Create custom illustrations for blog articles or social media"19 - "Edit an existing image by replacing a region using an inpainting mask"20 agents: [claude-code, openai-codex, gemini-cli, cursor]21---2223# DALL-E 3 API2425## Overview2627DALL-E 3 is OpenAI's image generation model, accessible via the OpenAI Python SDK. It supports text-to-image generation with high prompt fidelity, image editing with alpha-channel masks, and returns a "revised prompt" showing how the model interpreted your request.2829## Setup3031```bash32pip install openai python-dotenv33export OPENAI_API_KEY="your_api_key_here"34```3536## Core Concepts3738- **Generations** (`/v1/images/generations`): Create a new image from a text prompt.39- **Edits** (`/v1/images/edits`): Modify an existing image by painting over a masked region.40- **Variations** (DALL-E 2 only): Generate variations of an existing image.41- **Revised prompt**: DALL-E 3 rewrites your prompt for safety and quality — always log `revised_prompt` to understand the actual input.42- **Response format**: `url` (temporary CDN link, expires in 1 hour) or `b64_json` (base64-encoded PNG).4344## Instructions4546### Step 1: Initialize the client4748```python49import os50import base6451import requests52from pathlib import Path53from openai import OpenAI5455client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])56```5758### Step 2: Generate an image (text-to-image)5960```python61def generate_image(62 prompt: str,63 model: str = "dall-e-3",64 size: str = "1024x1024",65 quality: str = "standard",66 style: str = "vivid",67 output_path: str = "output.png"68) -> dict:69 """70 Generate an image with DALL-E 3.7172 size options: 1024x1024 | 1792x1024 | 1024x179273 quality options: standard | hd74 style options: vivid (dramatic) | natural (more realistic)75 Returns dict with saved path and revised_prompt.76 """77 response = client.images.generate(78 model=model,79 prompt=prompt,80 size=size,81 quality=quality,82 style=style,83 n=1,84 response_format="b64_json"85 )8687 image_data = response.data[0]88 revised_prompt = image_data.revised_prompt89 print(f"Revised prompt: {revised_prompt}")9091 # Decode and save92 img_bytes = base64.b64decode(image_data.b64_json)93 Path(output_path).write_bytes(img_bytes)94 size_kb = len(img_bytes) // 102495 print(f"Saved: {output_path} ({size_kb} KB)")9697 return {"path": output_path, "revised_prompt": revised_prompt}9899# Standard quality, vivid style100result = generate_image(101 prompt="A sleek electric car driving through a futuristic city at night, neon reflections on wet streets, cinematic",102 size="1792x1024",103 quality="standard",104 style="vivid",105 output_path="electric_car.png"106)107108# HD quality, natural style for photorealism109result = generate_image(110 prompt="A professional headshot of a confident businesswoman in a modern office, natural lighting, 50mm lens",111 size="1024x1024",112 quality="hd",113 style="natural",114 output_path="headshot.png"115)116```117118### Step 3: Image editing with inpainting mask119120```python121def edit_image(122 image_path: str,123 mask_path: str,124 prompt: str,125 size: str = "1024x1024",126 output_path: str = "edited.png"127) -> str:128 """129 Edit an image by replacing the masked region with generated content.130131 image_path: PNG file, RGBA or RGB, must be square, ≤ 4MB132 mask_path: PNG file with alpha channel. Transparent pixels = area to edit.133 Returns path to the edited image.134 """135 with open(image_path, "rb") as img_f, open(mask_path, "rb") as mask_f:136 response = client.images.edit(137 model="dall-e-2", # edits require dall-e-2138 image=img_f,139 mask=mask_f,140 prompt=prompt,141 size=size,142 n=1,143 response_format="b64_json"144 )145146 img_bytes = base64.b64decode(response.data[0].b64_json)147 Path(output_path).write_bytes(img_bytes)148 print(f"Edited image saved: {output_path}")149 return output_path150151# Example: replace the background of a product photo152edit_image(153 image_path="product.png", # Original product image154 mask_path="background_mask.png", # Alpha mask over background area155 prompt="A tropical beach at sunset as background",156 size="1024x1024",157 output_path="product_beach.png"158)159```160161### Step 4: Create a mask programmatically162163```python164from PIL import Image # pip install Pillow165import numpy as np166167def create_circular_mask(image_path: str, center_x: float = 0.5, center_y: float = 0.5,168 radius: float = 0.3, output_path: str = "mask.png") -> str:169 """170 Create an inpainting mask with a transparent circle.171 center_x/y: 0.0–1.0 relative position172 radius: 0.0–0.5 relative radius173 """174 img = Image.open(image_path).convert("RGBA")175 w, h = img.size176 mask = Image.new("RGBA", (w, h), (255, 255, 255, 255)) # fully opaque177178 cx, cy, r = int(w * center_x), int(h * center_y), int(min(w, h) * radius)179 mask_arr = np.array(mask)180 Y, X = np.ogrid[:h, :w]181 dist = np.sqrt((X - cx)**2 + (Y - cy)**2)182 mask_arr[dist <= r, 3] = 0 # transparent = area to edit183 Image.fromarray(mask_arr).save(output_path)184 print(f"Mask saved: {output_path}")185 return output_path186187create_circular_mask("product.png", center_x=0.5, center_y=0.5, radius=0.4, output_path="circle_mask.png")188```189190### Step 5: Batch generation191192```python193import time194195def batch_generate(prompts: list[str], size: str = "1024x1024",196 quality: str = "standard", output_dir: str = "output/") -> list[str]:197 """Generate multiple images with rate-limit handling."""198 Path(output_dir).mkdir(exist_ok=True)199 paths = []200 for i, prompt in enumerate(prompts):201 try:202 out_path = f"{output_dir}/image_{i:03d}.png"203 result = generate_image(prompt, size=size, quality=quality, output_path=out_path)204 paths.append(result["path"])205 time.sleep(1) # respect rate limits (5 images/min on standard tier)206 except Exception as e:207 print(f"Error on prompt {i}: {e}")208 time.sleep(5)209 return paths210211products = [212 "A wooden cutting board with fresh vegetables, overhead shot, natural light",213 "A ceramic mug with steam rising, cozy kitchen background, warm tones",214 "A leather wallet on a marble surface, minimal style, luxury feel"215]216batch_generate(products, quality="hd", output_dir="product_shots")217```218219## Parameters reference220221| Parameter | Values | Description |222|-----------|--------|-------------|223| `model` | `dall-e-3`, `dall-e-2` | DALL-E 3 = generations only; DALL-E 2 = edits + variations |224| `size` | `1024x1024`, `1792x1024`, `1024x1792` | Output dimensions (DALL-E 3) |225| `quality` | `standard`, `hd` | `hd` has finer details, costs 2x credits |226| `style` | `vivid`, `natural` | `vivid` = dramatic; `natural` = more realistic |227| `response_format` | `url`, `b64_json` | URL expires in 1 hour; b64_json is permanent |228| `n` | `1` (DALL-E 3) | DALL-E 3 supports n=1 only |229230## DALL-E 3 behaviors to know231232- **Prompt rewriting**: DALL-E 3 automatically rewrites prompts. Log `revised_prompt` to understand what was actually generated.233- **Safety filters**: Some content is refused and returns an error. The revised prompt handles most edge cases automatically.234- **No n>1**: DALL-E 3 only generates 1 image per API call. Use a loop for batches.235- **Edits use DALL-E 2**: The `/v1/images/edits` endpoint only supports DALL-E 2.236- **URL expiry**: Response URLs expire after 1 hour. Always download and store images immediately.237238## Guidelines239240- Use `quality="hd"` and `style="natural"` for photorealistic product images.241- Use `quality="standard"` and `style="vivid"` for illustrations, concept art, and marketing visuals.242- For best results, be specific: include subject, style, lighting, camera angle, and mood in the prompt.243- Use `b64_json` instead of `url` format to avoid download failures on slow networks.244- Rate limits: ~5 images/minute on standard tier. Add `time.sleep(1)` between batch requests.245- Store API keys in environment variables — never hardcode them.