Your editor shows a white selection over a black background. The preview looks correct, the upload succeeds, and the resulting image changes the wrong area—or barely changes at all. Before rewriting the prompt, inspect the file that actually crossed your backend boundary. A picture of a selection and a machine-readable editing mask can look similar while carrying different information.

This workshop builds a small input preflight for backend developers shipping image tools and e-commerce SaaS. It starts with a deliberately flawed black-and-white file, converts a declared selection into alpha, binds that mask to a normalized source, and builds an ordered multipart request. The useful result is a reproducible answer to “what did we send?” before spending time evaluating model behavior.

If your initial problem is choosing an endpoint or replacing an old integration, the separate GPT Image API migration guide covers that decision. Here, we assume you have identified an image-edit route and want to prove the inputs are coherent. The model identifier remains configuration, so the example does not depend on a model name copied from an older tutorial.

Start with the alpha contract, not the thumbnail

The OpenAI image-edit reference specifies a valid PNG mask below 4 MB, with dimensions matching the input image. Fully transparent mask pixels identify the edit area; with multiple inputs, the mask targets the first image. markup and mask cannot be combined. These are request requirements; the stricter binary-mask rules in our validator below are application choices.

The W3C PNG specification distinguishes color samples from opacity. In an eight-bit alpha channel, zero means transparent and 255 means opaque. Consequently, painting a pixel black does not itself make that pixel transparent. A plain RGB black-and-white PNG has no explicit alpha channel at all.

Our debugging example uses an 80-by-60 canvas with a 20-by-20 selection. The product UI defines white as editable. That definition must be explicit because another brush tool may export black as editable. Neither convention should be inferred from which color occupies less of the image. A large background replacement can legitimately select most of a canvas.

Selection exportDeclared intentAlpha written by this workshop
White pixelsEditable when editable_color="white"0
Black pixelsOutside that selection255
Gray or soft edge pixelsUndeclared interpretationReject and ask the editor to resolve the edge
Entirely white selectionWhole-image operationReject in this partial-edit workflow

These rules make a support report more useful. Instead of “the mask is black,” your application can report the selected area, the polarity choice, and the exact source revision. Do not use background="transparent" as a repair for this input problem: that parameter concerns generated output, whereas this preflight checks the separate file supplied as editing guidance.

Freeze the coordinate system before the user draws

Consider a phone image whose stored raster is landscape but whose orientation metadata makes a viewer display it upright. A browser can present a portrait editing surface while another decoder reports the stored landscape dimensions. If you create a mask against one representation and upload the other, stretching the mask until the dimensions match may conceal the mistake while moving the selection.

Our policy is to normalize the source first, save a new canonical PNG, and display that exact asset in the selection editor. Pillow's ImageOps documentation describes exif_transpose, which applies the orientation transform and removes the orientation tag. After that operation, the application treats pixel coordinates as the source of truth. It does not rotate the finished mask independently or attempt to guess which coordinate system a user intended.

Dimensions alone still leave a blind spot. Two product photographs can both be square; a square can also be rotated without changing its size. Bind the brush session to a source identifier and a digest of the normalized upload bytes. If the customer replaces the product photo while keeping an old selection, invalidate the selection instead of silently applying it to the replacement.

The distinction is operationally useful in queues. Store the normalized source and its mask as immutable job inputs, then enqueue their references together. A worker should not fetch a mutable “current product image” URL later. The broader queue architecture in production image pipelines is useful background; source binding is the extra check needed at this editing boundary. The older-model tutorials linked here, including the n8n workflow below, provide historical workflow background. Obtain current model IDs and availability from your chosen route instead of reusing their older code snippets.

Build the preflight in Python

Install Pillow and HTTPX in your application's isolated environment. Save the following as image_mask_preflight.py. It intentionally standardizes prepared assets to static RGBA PNG files. Other valid image representations require their own deliberate conversion path; this example does not silently accept every PNG variant.

The implementation uses Pillow's Image API to inspect and write channels. Its histogram makes the selection count measurable. We reject partial alpha, all-transparent selections, and unresolved orientation because the workshop implements one specific product behavior: a binary selection covering part of an already normalized source.

from hashlib import sha256
from pathlib import Path
import warnings
from PIL import Image, ImageOps

MASK_LIMIT = 4_000_000  # Conservative local interpretation of 4 MB.
Image.MAX_IMAGE_PIXELS = 20_000_000  # Application policy, not an API limit.
warnings.simplefilter('error', Image.DecompressionBombWarning)


def digest(path):
    return sha256(Path(path).read_bytes()).hexdigest()


def read_static(path):
    with Image.open(path) as im:
        if getattr(im, 'n_frames', 1) != 1:
            raise ValueError('animated input is outside this workflow')
        im.load()
        return im.copy(), im.format


def canonical_source(src, dst):
    im, _ = read_static(src)
    upright = ImageOps.exif_transpose(im).convert('RGBA')
    upright.info.clear()  # Export explicit pixels, without inherited metadata.
    upright.save(dst, format='PNG')


def require_canonical(path):
    im, fmt = read_static(path)
    if fmt != 'PNG' or im.mode != 'RGBA':
        raise ValueError('expected the prepared RGBA PNG')
    if im.getexif().get(274, 1) != 1:
        raise ValueError('normalize orientation before drawing the selection')
    return im


def make_mask(source, selection, output, *, editable_color):
    base = require_canonical(source)
    brush, _ = read_static(selection)
    if brush.getexif().get(274, 1) != 1:
        raise ValueError('selection must use canonical coordinates')
    if brush.size != base.size:
        raise ValueError('selection dimensions differ; redraw, do not stretch')
    if editable_color not in {'white', 'black'}:
        raise ValueError('declare editable_color as white or black')
    luminance = brush.convert('L')
    histogram = luminance.histogram()
    if sum(histogram[1:255]):
        raise ValueError('selection must be binary; resolve soft edges explicitly')
    selected_value = 255 if editable_color == 'white' else 0
    alpha = luminance.point(lambda p: 0 if p == selected_value else 255)
    mask = Image.new('RGBA', base.size, (0, 0, 0, 255))
    mask.putalpha(alpha)
    mask.save(output, format='PNG')
    return {'source_sha256': digest(source), 'mask_sha256': digest(output),
            'editable_color': editable_color, 'size': list(base.size)}


def validate_pair(first_image, mask_path, manifest):
    if digest(first_image) != manifest['source_sha256']:
        raise ValueError('first image differs from the selection source')
    if digest(mask_path) != manifest['mask_sha256']:
        raise ValueError('mask bytes changed after selection export')
    base = require_canonical(first_image)
    mask = require_canonical(mask_path)
    if mask.size != base.size or list(base.size) != manifest['size']:
        raise ValueError('source/mask/manifest dimensions differ')
    if Path(mask_path).stat().st_size >= MASK_LIMIT:
        raise ValueError('mask exceeds the local upload budget')
    counts = mask.getchannel('A').histogram()
    if counts[0] == 0:
        raise ValueError('no fully transparent editable pixels')
    if counts[255] == 0 or sum(counts[1:255]):
        raise ValueError('this workflow requires a binary, partial selection')
    return {'size': list(base.size), 'editable_pixels': counts[0],
            'editable_fraction': counts[0] / (base.width * base.height)}

The 4,000,000-byte budget is deliberately conservative, avoiding an assumption about decimal versus binary megabytes. The 20-million-pixel warning threshold is an application decoding policy, not an advertised API limit or a complete upload security system. Production services should also bound compressed input bytes, worker memory, file count, and queue duration according to their infrastructure.

There is an important distinction between conversion and validation. make_mask converts an explicit editor convention. validate_pair does not “helpfully” repair a submitted mask: it checks the exported files and their manifest. Keeping those operations separate prevents a validator from reversing the customer's intent merely to make a failing job pass.

The manifest belongs to the server-side editing session. Do not let a client replace both a file and its claimed digest and then interpret the matching values as proof of authorization. Here, hashes detect accidental substitution and stale revisions. Access control still determines which source the customer may edit. In a worker, keep the validated files immutable between checking them and reading their bytes for upload.

Reproduce the opaque-mask failure without an API call

Run this next script in the same directory. It creates synthetic pixels, so no customer photograph or external service is involved. The brush image is intentionally an opaque visual selection. Only the converted output is used as the upload mask.

import json
from pathlib import Path
from PIL import Image, ImageDraw
from image_mask_preflight import make_mask, validate_pair

root = Path('image-fixtures')
root.mkdir(exist_ok=True)
source, selection, mask = [root / name for name in
                           ['source.png', 'selection.png', 'mask.png']]
canvas = Image.new('RGBA', (80, 60), (160, 190, 210, 255))
ImageDraw.Draw(canvas).rectangle((10, 20, 29, 39), fill=(220, 50, 50, 255))
canvas.save(source)
Image.new('RGBA', (80, 60), (70, 150, 100, 255)).save(root / 'reference.png')
brush = Image.new('L', canvas.size, 0)
ImageDraw.Draw(brush).rectangle((10, 20, 29, 39), fill=255)
brush.save(selection)  # Looks like a mask, but has no alpha channel.
manifest = make_mask(source, selection, mask, editable_color='white')
(root / 'manifest.json').write_text(json.dumps(manifest), encoding='utf-8')
report = validate_pair(source, mask, manifest)
assert report['editable_pixels'] == 400
assert abs(report['editable_fraction'] - 1 / 12) < 1e-12
print(report)

The successful preflight reports 400 editable pixels, or one twelfth of the canvas. Changing the declared polarity to black yields 4,400 editable pixels. Both outputs have identical dimensions, and both can be valid files, but they encode opposite user intentions. That is why a polarity setting deserves a visible product decision and a test assertion.

Keep several negative fixtures alongside the happy path. An RGBA mask filled with alpha 255 should fail despite having the right filename. A transposed mask should fail size validation. A different source with the same dimensions should fail the digest check. A source carrying unresolved orientation should fail before uploading. A partially transparent edge should fail under this workshop's binary-selection policy, even if another application deliberately supports softer selections.

For this article, fourteen offline preflight tests passed, including both polarities, the conservative size boundary, orientation normalization, stale source binding, and malformed selection cases. A separate multipart construction test passed as well. These results establish local behavior only; they do not establish image quality or prove that a particular gateway route accepts masks.

Preserve source-first ordering in the multipart body

A request builder often begins with a dictionary keyed by filename, then sorts those keys to make logging predictable. That is a poor abstraction for this workflow. Source order carries meaning. Keep an explicit ordered list with the selected source first and optional references afterward; never derive the first slot from upload completion time or alphabetical filenames.

The HTTPX multipart documentation shows how file tuples carry filenames and content types while data carries normal form fields. Let the client construct the multipart boundary. Manually supplying only Content-Type: multipart/form-data can leave the header disconnected from the actual encoded body.

Save this builder as image_edit_request.py. It accepts full route configuration and runs the pair validation immediately before assembling the request. Every additional reference must already have passed through the same canonical image preparation path.

from pathlib import Path
from image_mask_preflight import validate_pair, require_canonical


def build_edit_request(client, *, image_paths, mask_path, manifest,
                       edit_url, model, api_key, prompt):
    if not image_paths:
        raise ValueError('place the selected source first')
    report = validate_pair(image_paths[0], mask_path, manifest)
    files = []
    for path in image_paths:  # Preserve explicit source-first ordering.
        require_canonical(path)
        files.append(('image[]', (Path(path).name,
                                  Path(path).read_bytes(), 'image/png')))
    files.append(('mask', ('mask.png', Path(mask_path).read_bytes(), 'image/png')))
    request = client.build_request(
        'POST', edit_url,
        headers={'Authorization': f'Bearer {api_key}'},
        data={'model': model, 'prompt': prompt}, files=files)
    return request, report

Call it from a worker after loading the server-owned manifest:

import json
import os
from pathlib import Path
import httpx
from image_edit_request import build_edit_request

root = Path('image-fixtures')
manifest = json.loads((root / 'manifest.json').read_text(encoding='utf-8'))
with httpx.Client(timeout=120.0) as client:
    request, report = build_edit_request(
        client,
        image_paths=[root / 'source.png', root / 'reference.png'],
        mask_path=root / 'mask.png', manifest=manifest,
        edit_url=os.environ['IMAGE_EDIT_URL'],
        model=os.environ['IMAGE_MODEL'],
        api_key=os.environ['IMAGE_API_KEY'],
        prompt='Change the selected red square to green; keep the composition.')
    response = client.send(request)  # This line makes a real API request.
    response.raise_for_status()
    print(response.status_code, response.headers.get('x-request-id'), report)

Set IMAGE_EDIT_URL to the complete, verified edit endpoint and IMAGE_MODEL to an exact model identifier supported by that route. For OpenAI directly, the edit endpoint is https://api.openai.com/v1/images/edits. For a gateway, use its documented route and field contract rather than assuming that a working text request proves image-edit compatibility. The credential belongs in the worker environment, not in the browser's drawing tool.

The request test parses the constructed multipart body without sending it. It checks the two image[] parts remain in source-then-reference order, that the uploaded source bytes match the fixture, that a separate mask part exists, and that the boundary is present. It also checks there is no markup field. This is a stronger regression guard than merely asserting that the request builder returned an object.

Triage failures at the boundary that owns them

When a preflight fails, give the editor a repairable explanation. “Your photo changed after this selection was drawn” is actionable; “invalid image” is not. Preserve the original draft selection so the user can redraw or reconfirm it against the correct asset. Avoid automatically resizing a mask just because the service expects another shape: the customer must still recognize the selected region after any coordinate transformation.

A route rejection after preflight calls for a different investigation. Record the endpoint, configured model, field names, image count, normalized dimensions, mask byte count, and provider request identifier when returned. Keep secrets and raw image contents out of routine logs. Compare that evidence with the route's actual contract before changing the prompt. A model-level interpretation problem cannot explain a file that was rejected before the model received it.

Timeouts deserve their own job state. An interrupted connection does not tell your application whether an external operation completed. Avoid a blind loop that creates multiple edit jobs when the customer clicks again. The request identity pattern discussed in preventing duplicate API requests is relevant here, even though its original example uses a coding workflow.

For a no-code orchestration layer, place this preparation in a backend service and pass stable asset references into the workflow. The n8n image automation guide can help with that orchestration context. Keep the byte-level preflight close to the upload operation so an intermediate export cannot flatten away the alpha channel after validation.

A correct input still needs a reviewable product promise

The OpenAI image-generation guide says mask editing guides the model and may not follow the mask's exact shape precisely. A successful preflight therefore establishes input consistency, not a guarantee that all other pixels remain unchanged. Do not promise a customer that this feature locks a logo, face, label, or product silhouette with pixel-level certainty.

Write the prompt around the desired change and the surrounding details the reviewer should check. For the synthetic example, changing a red square to green is enough. In a real catalog workflow, name the object and its intended material or color, then identify important details to inspect. A short acceptance checklist is easier for a human to apply than an ambitious prompt that quietly becomes a contractual promise.

Some applications need exact preservation of a protected region. Treat that as a separate implementation requirement with its own compositing and review decisions. Decide whether seams, lighting changes, or mismatched edges are acceptable before introducing a mechanical composition step. The preflight here does not solve those visual questions. It gives the downstream workflow a trustworthy statement of the selection that was submitted.

Record that statement with the job: source revision, mask revision, polarity, selected pixel count, prompt revision, route, and model configuration. The application design discussed in building a production image app becomes easier to support when every edit carries this compact input history. You can then distinguish a stale selection from an unsatisfactory generation without asking a customer to reconstruct what they clicked.

Verify the image-edit route before expanding usage

If you are evaluating TreeRouter, begin at TreeRouter's Get started page and verify the exact image-edit route you intend to use. Ask for the accepted model identifier, multipart image field naming, mask handling, size limits, and error behavior. Then submit a small non-sensitive fixture only after those details are confirmed. This article's offline results do not claim that TreeRouter currently supports every illustrated mask feature.

The broader gateway checks before paying use another model family, but the purchasing question transfers: can the specific route perform the operation your product needs? For this workflow, a successful text call or unmasked generation does not answer that question. Keep your acceptance record narrow: validated inputs, accepted masked edit, reviewable output, and traceable request evidence.

FAQ

Why does my black-and-white mask look right but fail preflight?

The preview may show only color information. Inspect the actual exported mode and alpha histogram. In this workshop, the selection image is an intermediate artifact; make_mask creates the upload file. If an image optimizer later flattens that file, regenerate it from the original selection and repeat validation on the final upload bytes.

Should I resize the mask when GPT Image mask dimensions differ?

First identify which asset the editor displayed. A mismatch can indicate that normalization, cropping, or a source replacement happened after selection. Regenerate the selection against the canonical source. If your product intentionally supports resizing, apply a documented coordinate transform to both assets and require a fresh visual confirmation.

Does this validator guarantee the intended object was selected?

No. It checks representation and binding, not semantic intent. A user can draw a perfectly valid selection over the wrong object. Show the selection overlay on the canonical source before submission, and preserve that preview with the editing session when your retention policy permits it.

Can I combine an annotation overlay with this mask request?

The builder intentionally provides only a mask workflow. Keep any annotation-based mode separate, including its export rules and validation. Do not carry a stale overlay field into this request when a customer switches editing modes. An explicit mode enum in your backend is easier to validate than a collection of optional files.

Why reject an all-transparent or partially transparent mask?

Those rejections are local product choices. This example is designed to make a partial, binary selection unambiguous. A whole-image edit or a soft-edge workflow needs a separate acceptance contract and fixtures. Avoid weakening the checks just to admit a file whose intended behavior has not been defined.

Technical references