This page is a hands-on guide to localized editing (inpainting) with
gpt-image-2 via POST /v1/images/edits, by uploading an image + mask + prompt. For full parameter reference and the interactive Playground, see Image Edit API Reference.Core Principle: the Alpha Channel Defines the Edit Region
A localized edit request consists of three parts:| Mask region | Alpha value | Effect |
|---|---|---|
| Fully transparent | 0 | Model may edit |
| Fully opaque | 255 | Preserve original as much as possible |
| Semi-transparent | 1–254 | Transition zone; do not rely on it as a precise rule |
A Visual Example
Suppose the original image is 1024×1024:The Mask Is Not a Hard Crop
GPT Image masks are not absolute pixel-level constraints like Photoshop selections. Officially, mask editing remains prompt-guided editing: the model uses the mask as a reference but does not guarantee strict adherence to every pixel boundary. You may therefore see:- Slight shadow changes outside the mask
- Object edges extending beyond the mask
- Coordinated lighting and reflection changes
- Minor background repainting
- Transition effects near mask boundaries
Improving Edit Stability
Don’t just write “change it to a red shirt”. Write instead:- Make the mask slightly larger than the target object’s edges
- Don’t just cover the object’s center — include edges, shadows, and reflections
- Explicitly state what must remain unchanged
- If the edit region is too small, enlarge the mask
- When absolute preservation is required, do a final pixel composite yourself (see below)
To Mask or Not to Mask? Trade-offs vs Prompt-Only Editing
A common question: modern AI can already “edit exactly what you point at” with plain language — why bother making a mask? It’s true thatgpt-image-2 without a mask, given just “replace the cup on the left side of the table with flowers”, usually edits the right spot — instruction following is strong, and for casual edits a prompt alone is enough. But a mask solves the cases where language is ambiguous, or unambiguous but still not reliable enough:
| Scenario | Prompt only | Prompt + Mask |
|---|---|---|
| Only one target object in the frame | ✅ Sufficient; a mask is overkill | Unnecessary |
| Multiple similar objects, edit just one (change only the middle person’s outfit) | ⚠️ Easily hits the wrong twin | ✅ Spatially pinned, zero ambiguity |
| Strict boundaries (product shots / UI screenshots / ID layouts) | ❌ Whole-image regeneration; areas drift | ✅ With pixel compositing, strictly unchanged |
| Batch pipelines (repeatedly replacing the same region in a fixed layout) | ⚠️ Unstable across runs | ✅ Masks are programmable and reproducible |
| Precise shape / position control (move an object to exact coordinates) | ❌ Language can’t express pixel positions | ✅ The mask is pixel coordinates |
File Requirements at a Glance
| Item | Requirement |
|---|---|
| Image format | PNG / JPG / WebP, each under 50MB |
| Number of input images | Up to 16 (repeat the image[] field) |
| Mask format | PNG with an alpha channel (required) |
| Mask dimensions | Must exactly match the first image (even 1 pixel off fails) |
| Mask file size | Under 4MB |
| Mask scope | Applies only to image[0] (the first image) |
Python Example
cURL Example
The image edit endpoint requiresmultipart/form-data — you cannot submit the image and mask as plain JSON fields:
image[] field name as in the official examples.
Node.js Example
Where Do Masks Come From? Five Common Methods
People often find masks intimidating — “it has to match the original image pixel for pixel”. The key realization: you almost never draw a mask from scratch; you derive it from the original image. Whether via code, a photo editor, or a web canvas, the flow is always “open the original → mark regions on it → export”, so matching dimensions are automatic.| Method | Best for | Effort |
|---|---|---|
| ① Code generation (draw regions with PIL) | Fixed-layout batch jobs, known coordinates | Low (a few lines) |
| ② Manual erasing in a photo editor | One-off precision edits, complex shapes | Low (basic selection skills) |
| ③ Web brush canvas | Building “brush to edit” into your own product | Medium (front-end Canvas) |
| ④ AI auto-segmentation (SAM family) | One click / one phrase → precise mask | Medium (deploy or call a segmentation service) |
| ⑤ Convert a black-and-white mask to alpha | Consuming B&W masks from other tools | Low (a few lines) |
Method 1: Generate a Transparent Mask Programmatically
Set a rectangular region to transparent (editable):(255, 255, 255, 255)= opaque, preserved region(0, 0, 0, 0)= transparent, editable region
Method 2: Manual Erasing in a Photo Editor
Any editor that supports transparent PNGs (Photoshop, GIMP, Krita, Photopea, etc.) can produce a mask — it boils down to one action: erase the region you want edited into transparency. In Photoshop:- Open a copy of the original image (working on the original itself guarantees matching dimensions)
- If the layer is a locked “Background”, double-click to convert it to a normal layer (background layers don’t support transparency)
- Select the region to modify with the Lasso / Quick Selection / Object Selection tool
- Press Delete — the selection becomes the transparent checkerboard
- “Export As PNG” (with transparency enabled) — the result is a valid alpha mask
Layer → Transparency → Add Alpha Channel, select, Delete, export as PNG.
Method 3: Web Brush Canvas
The “brush over what you want changed” interaction in AI photo apps is just an alpha mask generated live in the browser, built around a single Canvas API property. See How Brush-Style Editing Works below.Method 4: One-Click Masks via AI Segmentation
If even brushing feels like work, let a segmentation model do it. Meta’s open-source SAM (Segment Anything Model) family is the mainstream option:- Click to mask: click an object once and the model returns its pixel-accurate outline (down to hair-strand edges)
- Text to mask: SAM 3, open-sourced in November 2025, accepts concept-level text prompts like “all yellow taxis” or “players wearing red jerseys” and returns masks for every matching instance (model and code at
github.com/facebookresearch, overview atai.meta.com) - Subject / background split: open-source tools like
rembgseparate subject from background in one command — the background region can directly serve as a “change only the background” mask
Method 5: Convert a Black-and-White Mask to an Alpha Mask
If you already have a mask where “black = edit, white = keep”:Validate the Mask Before Uploading
Manyinvalid_image_file errors happen because a file has a .png extension but only RGB channels and no alpha. Run this before uploading:
Mask Shapes and How Brush-Style Editing Works
Masks Can Be Any Irregular Shape
A mask is fundamentally a per-pixel bitmap, not a geometric shape — every pixel carries its own alpha value. So:- Rectangles and circles are just the simplest examples
- A person-shaped silhouette, hair-strand edges, a freehand scribble, or multiple disconnected patches are all valid
- In practice most masks are irregular: they follow the target object’s outline, slightly expanded
How Brush-Style Editing Is Implemented
The “brush where you want changes” interaction in photo apps is surprisingly simple on the front end: two stacked layers, with the brush “erasing” the top one into transparency.destination-out (new strokes “carve out” existing pixels):
- Coordinate conversion: the canvas is usually scaled down by CSS on the page; convert stroke coordinates back by
naturalWidth / clientWidth, or the mask will be misaligned - Undo: snapshot with
ctx.getImageData()before each stroke and restore withputImageData() - Mask dilation: users tend to brush only the object’s center — programmatically expand the mask a few pixels before submitting (the “Expand Mask” button in professional tools); on the Python side use
PIL.ImageFilter.MaxFilteror OpenCV’scv2.dilate - Semi-transparent preview: draw the user-facing highlight (e.g. translucent red) on a separate preview layer, keeping the exported mask layer strictly binary opaque/transparent
Going Further: Click or Text to Mask
One step beyond brushing is replacing “human strokes” with “model inference”:Multiple Reference Images + Mask
A typical scenario: outfit swap (first image is the person, followed by style / fabric references; the mask marks the clothing region):Strictly Preserving Content Outside the Mask (Pixel-Level Post-Processing)
Since the model may slightly alter content outside the mask, for pixel-accuracy scenarios (product shots, ID layouts, fixed UI screenshots), composite the region outside the mask back from the original after generation:Common Errors
invalid_image_file / Invalid image file or mode
invalid_image_file / Invalid image file or mode
Common causes:
- The mask is not a valid PNG, or the file is corrupted
- The extension says PNG but the actual encoding is not PNG
- Abnormal image mode (CMYK, palette mode, missing alpha)
- Wrong MIME type on upload
- The file stream was already consumed or closed before the request
Image and mask dimensions don't match
Image and mask dimensions don't match
Even a 1-pixel difference fails. Fix:
Black-and-white mask has no alpha channel
Black-and-white mask has no alpha channel
RGB / L / P modes are not enough — the mask must be RGBA. Use “Method 2” above to convert.Transparent background request fails
Transparent background request fails
The mask itself can contain transparency (that is how you mark the edit region), but Use
gpt-image-2 does not support transparent output backgrounds:"opaque" or "auto" for background; passing "transparent" returns an error.response_format=url returns no image
response_format=url returns no image
GPT Image models always return Base64 data;
response_format only applies to legacy DALL·E 2 behavior. Read the result via:Content-Type isn't multipart/form-data
Content-Type isn't multipart/form-data
Usually caused by manually setting the
Content-Type header (losing the boundary), or a middle layer parsing the multipart request into JSON before forwarding. Let your HTTP client generate the multipart headers automatically.Size Parameters
gpt-image-2 supports flexible dimensions, subject to all of the following:
1024x1024, 1536x1024, 1024x1536, 2048x2048, 2048x1152, 3840x2160, 2160x3840, auto. Square images usually generate faster.
Production Request Template
Related Pages
Image Edit API Reference
Full parameter reference and interactive Playground
GPT-Image-2 Overview
Model capabilities, pricing, and version notes
Official references (copy into your browser):
- Model page:
developers.openai.com/api/docs/models/gpt-image-2 - Image edit API reference:
developers.openai.com/api/reference/python/resources/images/methods/edit/ - Image generation guide:
developers.openai.com/api/docs/guides/image-generation