This guide was prepared with AI assistance using the linked documentation. Code examples are illustrative; verify them against your environment and current API documentation before use.
An AI image edit starts with a source image and a requested change. The difficult part is deciding whether the result is safe and useful enough to publish. A model might replace a background convincingly while changing a product label, altering a person's features, or inventing a detail that wasn't in the original.
This guide walks through an editing workflow for a small product team. You'll define an edit, keep the source and reference files distinct, call an image-editing API, compare the candidate with the original, and record an approval or rejection. The example uses OpenAI's Image API, but the review process is useful with any image editor.
The code is a local prototype. It is not a public upload service, an automatic approval system, or proof that a particular model will preserve a detail. Check model availability, current input limits, terms, and pricing in the linked documentation before using it. The source image still needs an appropriate license or permission, and the finished result needs a review suited to where it will appear.
Start with an edit brief
Imagine an online store that wants to replace the background behind a ceramic mug. The mug's shape, glaze, handle, and printed mark must remain accurate. The background should become a dark tabletop with soft window light. The finished image will appear on a product page, where a customer may rely on the image to decide what to buy.
That brief contains two kinds of instruction: what may change and what must remain dependable. Both belong in the request and in the review checklist. A result that looks attractive but changes the shape of the handle has failed the task, even if the new background is excellent.
Write a brief with the following fields before producing candidates:
| Field | Example |
|---|---|
| Source | Approved front view of the ceramic mug |
| Desired change | Replace the background with a dark tabletop |
| Preserve | Mug shape, color, handle, printed mark, and orientation |
| Placement | Product detail page and square catalog card |
| Reviewer | Person responsible for product accuracy |
| Failure condition | The mug or its mark differs from the real product |
| Fallback | Use the original photograph |
The reviewer may add requirements that aren't obvious to the person writing the prompt. A product manager might know that a safety marking must be legible. A designer might know that a heading will overlap the top-left corner. A support team might know that a particular angle causes customers to mistake one product version for another. Capture those needs before the first edit.
Choose the source of truth
Keep an original source image separate from every candidate. The original is the reference for what the model was asked to preserve; an edited candidate is a proposal. Save a stable asset identifier or content hash for the source so reviewers can be confident they are comparing the correct files.
For product imagery, the source of truth may also include a physical product, an approved brand asset, or a specification. A model cannot establish that an image accurately represents a product it has never seen. If exact color or geometry matters, compare the output against the approved reference and, where necessary, a real item under appropriate viewing conditions.
Don't repeatedly save over the original during experimentation. Keep candidate files under separate identifiers and make the approved image explicit. If an edit fails review, the original remains available. If a later candidate is approved and then found to be misleading, the team needs a way to restore the previous approved asset.
A source image can include metadata, private information, or content owned by a third party. Before sending it to an API, confirm that the team is authorized to process it and that the recipient, retention settings, and intended use are acceptable. Local possession of a file doesn't automatically grant permission to send it to a third-party service.
Pick the editing interface
OpenAI documents two routes for image editing. The Image API has an edits endpoint for modifying an image with a prompt and optional supporting inputs. It is a good fit for a single edit request that your application will manage. The Responses API can use an image-generation tool in a conversation, which can be useful when a user wants to discuss and refine a sequence of edits.
The interfaces are related but their request and response structures differ. With the Image API, you select an image model on the edit request. With the Responses API, you select a supported mainline model and configure the image-generation tool. Consult the image generation and editing guide and image-generation tool guide for current choices.
The example below uses the Image API because it shows the simplest single-request path. For a conversational editor, you still need to decide how a user selects an earlier approved image, what context is sent on the next turn, and how the application distinguishes a draft from an approved output. A long conversation is not a substitute for a versioned asset record.
OpenAI notes that organization verification may be required for some image models. Check that the selected model is available to your API project before treating an access error as a problem with the image or prompt. API model support changes over time; use the current reference when implementing or maintaining the integration.
Prepare a useful reference
Choose an input that shows the subject clearly at a size appropriate to the requested edit. A low-resolution image with a tiny logo may not contain enough detail to judge whether the logo was preserved. A compressed image with heavy artifacts can make edges and text difficult to review. Use the best authorized source that fits the API and your application's limits.
If you supply more than one image, explain each image's role. One file may be the object to edit; another may show a desired color palette or a reference background. Avoid leaving the model to infer whether a reference is a source to preserve or an element to add. The current API supports multiple images for supported models, but the exact number, file formats, and size limits should be checked in the edit endpoint reference.
References guide a result; they don't guarantee pixel-perfect copying. This matters for packaging, logos, legal labels, interfaces, maps, and other content where small changes carry meaning. If exact preservation is a requirement, compare at full resolution and consider a conventional compositing workflow that retains the original subject pixels. An AI edit and a deterministic cutout solve different problems.
Maintain a short asset manifest for your team: source ID, reference IDs, intended use, permission status, and the person who can approve the result. Don't put private source images into a public web directory simply because an approved derivative may later be published.
Write a specific edit instruction
A useful prompt describes the requested change, the subject to preserve, and the intended composition. It also sets expectations the reviewer can actually check. For the mug example:
Edit the supplied product photograph. Replace the background with a dark
charcoal tabletop and soft natural window light. Keep the mug's exact shape,
handle position, glaze color, orientation, and printed mark as shown in the
source. Do not add objects or text. Leave clear space around the mug for a
square product card.The preservation instructions are requests, not guarantees. The review must still compare the mug with the source. If a mark must be exact, preserve or reapply the approved mark through a controlled design process and have a person check the final image.
When a candidate fails, name the failure rather than adding vague praise or criticism. “The handle became narrower; keep its original width” gives the next attempt a concrete target. If the model repeatedly changes a detail, change the workflow: use a more suitable source, a different editing method, or manual compositing. More attempts aren't always the cheapest or safest solution.
Avoid including secrets, private customer information, or unnecessary personal details in prompts and reference images. The request is transmitted to the provider, even when the resulting file is saved on your own computer. Review the provider's current data controls and your organization's rules for the material.
A small Python example
This example sends one local source image to the Image API and saves a candidate PNG under a new filename. It deliberately doesn't overwrite the original or mark the candidate as approved. Use a synthetic or otherwise authorized image when testing.
You'll need Python, the official OpenAI SDK, an API key configured in your environment, and access to the selected model. A live request can incur charges. Check the current API pricing and your project's spending limits before testing. In a real application, pin dependencies and handle credentials using your approved secret manager.
Create a virtual environment and install the SDK:
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install openaiOn macOS or Linux, activate with source .venv/bin/activate. Set OPENAI_API_KEY through a secure mechanism appropriate to your environment. Don't paste a key into the script, commit it, or expose it in frontend JavaScript.
Save the following as edit_product.py:
import base64
from pathlib import Path
from openai import OpenAI
SOURCE = Path("source-mug.png")
CANDIDATE = Path("candidate-mug.png")
PROMPT = (
"Edit this product photograph. Replace the background with a dark "
"charcoal tabletop and soft natural window light. Keep the mug's shape, "
"handle position, glaze color, orientation, and printed mark as shown in "
"the source. Do not add objects or text. Leave space around the mug."
)
if CANDIDATE.exists():
raise FileExistsError("Choose a new candidate filename before running")
with SOURCE.open("rb") as source:
response = OpenAI().images.edit(
model="gpt-image-2.5-sunburst",
image=source,
prompt=PROMPT,
size="1024x1024",
quality="low",
output_format="png",
n=1,
)
if not response.data or not response.data[0].b64_json:
raise RuntimeError("The edit response did not contain image data")
candidate_bytes = base64.b64decode(response.data[0].b64_json, validate=True)
if not candidate_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
raise ValueError("The response did not have a PNG signature")
# Exclusive creation avoids overwriting an existing candidate.
with CANDIDATE.open("xb") as output:
output.write(candidate_bytes)
print("Candidate saved for review:", CANDIDATE)Run python edit_product.py after placing an authorized PNG at source-mug.png. Open both images side by side. Check the subject at full size, then inspect the candidate in the actual page or layout where it may be used. The PNG signature check catches a simple mismatch; it is not a complete image-integrity or security scan.
The example uses gpt-image-2.5-sunburst, a model listed in the current edit reference, and requests low quality for an initial candidate. Availability and settings depend on the account and may change. Check the live reference and compare the quality and cost settings that suit your task. The code doesn't implement retries, distributed coordination, access control, or durable storage.
The file is opened with exclusive creation after the API response arrives. That prevents an existing candidate from being overwritten, but two simultaneous runs can still both make paid API calls before one fails to create the file. A production job system needs a separate claim or idempotency strategy appropriate to its infrastructure. A write interrupted partway through can also leave a partial local candidate; use temporary files and a recovery plan when that matters.
What a successful response does—and doesn't—prove
The current GPT Image edit endpoint returns base64 image data. Decoding it and writing a PNG proves only that your program received and saved some bytes. It doesn't prove that the output matches the brief, that a visible product feature is accurate, or that the image may be used commercially.
Don't treat an HTTP success or a nonempty file as an approval event. A job can be marked candidate_ready when the final output is available. Approval should be a separate event tied to a reviewer and a specific version. If the image changes after approval, the new version should return to review.
The model's output is a new image, not an edit history with a guarantee about which original pixels were retained. If you need traceability, keep the original, candidate, request settings, and review decision as separate records. If a particular region must remain byte-for-byte unchanged, use a workflow that actually preserves that region and verify it independently.
Masks: useful guidance, not an exact boundary
A mask identifies an area to edit. The Images API edit reference says fully transparent areas of a PNG mask indicate where an edit should occur. It also says the mask applies to the first input image when multiple images are supplied. Match the mask dimensions to the source and check the current file requirements before sending it.
OpenAI's guide describes GPT Image masking as guidance and warns that the result may not follow the mask's exact shape. That means a mask around a background doesn't prove the subject outside it is unchanged. Review the boundary, nearby shadows, and the subject itself. For a product image, check both the obvious object and small marks near its edge.
To use a mask with the Python request above, open the separate PNG mask in binary mode and pass it as the mask argument to images.edit. Keep both files open until the request completes. The following fragment shows the shape of the call; it assumes client, source_path, mask_path, and prompt are already defined:
with source_path.open("rb") as source, mask_path.open("rb") as mask:
response = client.images.edit(
model="gpt-image-2.5-sunburst",
image=source,
mask=mask,
prompt=prompt,
output_format="png",
)The transparency semantics are easy to invert accidentally. Inspect the mask's alpha channel in an image editor, check its dimensions, and run a synthetic test before relying on it. When preserving a part is critical, plan for the possibility that the model changes it despite the mask.
Markup: point to a region with a separate overlay
For supported models, the Image API also documents a markup input: a transparent PNG overlay containing annotations such as a circle or sketch. The overlay is separate from the original image. It shows where a change is requested while the prompt explains what to do there.
The documented flow uses the original as the first image and a matching-size transparent overlay. The current guide says not to combine markup with mask; check the model-specific constraints and size limits in the live documentation. Additional input images can serve as references, but the annotation applies to the first image.
Markup can make a request easier to communicate to a human reviewer as well. A reviewer can see the source, the annotated region, and the result together. It still doesn't replace visual inspection: an annotation is an instruction to the model, not a locked layer in a graphics editor.
Choose a mask when the workflow is built around a region represented by transparency. Choose markup when the supported endpoint and model allow a more expressive annotation. If your requirement is “change only these exact pixels,” evaluate a conventional editing tool or composite the preserved part from the original under a controlled process.
Inspect the result in layers
Review begins with the whole image. Does the candidate fulfill the requested change? Is the composition suitable for the destination? Are there added objects, unexpected text, or visual artifacts that change what the image communicates?
Next, compare the protected subject against the original. For a physical product, inspect shape, proportions, color, logos, printed text, seams, controls, and accessories. Look at the edges and shadows as well: an altered shadow can make a product appear to have a different shape or position. For a person, consider consent and identity, and don't assume that a facial detail has remained accurate merely because the image looks plausible.
Then inspect at the intended display size. A full-resolution candidate may look fine in an editor but become confusing when cropped into a small card. Conversely, an artifact invisible in a thumbnail may be obvious when a customer opens a zoomed product image. Review both views if both are available on the site.
Use a side-by-side comparison and, where helpful, a difference overlay. Pixel differences can locate changed areas, but they don't tell you whether a change is acceptable. Lighting or compression can change many pixels while preserving the product's meaning; a one-character label change can affect only a small area and still be a serious defect. A person with the right context should make the final judgment.
Use a review rubric that leads to a decision
Keep the rubric short enough to use, but specific enough that two reviewers can discuss a disagreement. For the mug example, record each item as pass, fail, or needs clarification:
- The requested background and lighting are present.
- The mug's silhouette and handle match the approved source.
- The printed mark remains accurate and legible at the required size.
- No extra objects, marks, or text were introduced.
- The crop works in the product detail page and catalog card.
- The image doesn't imply a feature or accessory the customer won't receive.
- The source and intended use have been cleared under the team's policy.
Attach a short note to a failure. “Handle changed shape” tells the next editor what to fix. “Looks wrong” may be a valid first reaction, but it doesn't identify the defect or help another reviewer reproduce it. If the correct result depends on a fact the reviewer cannot verify, ask the subject-matter owner rather than assuming approval.
For consequential uses, expand the rubric and choose an appropriate reviewer. A product specialist, accessibility reviewer, legal reviewer, or editorial lead may need to approve different aspects. Make clear who can approve and who is responsible for publishing; the person who generated the image may not be the only person who should decide.
Record the candidate and decision
A basic asset record can contain a source ID, reference IDs, a candidate ID, the request settings, a status, and a reviewer note. Keep the model identifier and the date so you can understand which configuration produced the candidate. If an interface rewrites the prompt, consider retaining the effective prompt where the provider exposes it and where your data policy allows.
One possible lifecycle is:
Loading diagram…
Define what each transition means. candidate_ready means a final file exists. approved means the named reviewer accepted that exact version for a specified use. published means the publishing system actually points to it. withdrawn means a previously usable asset should no longer be shown. Don't infer publication from approval or approval from a successful API call.
Protect the review record from accidental edits. If someone replaces the bytes behind an approved asset ID, the audit trail no longer describes what was reviewed. Immutable versioned files, content hashes, and explicit publication pointers can help. A hash establishes whether bytes changed; it doesn't establish who created the file or whether the content is truthful.
Plan for revisions and rollback
Reviewers often request several changes. Keep each candidate separate and record which source and reference files produced it. A new candidate should not silently replace the one already under review. If two people edit simultaneously, use version IDs and a clear ownership process so one person's approval cannot be applied to another person's file.
When revising, decide whether to start from the original or a prior candidate. Starting from an edited result can preserve a good background, but repeated edits may accumulate unintended changes to the subject. Starting from the original can avoid some accumulated drift, but it may produce a different composition. Keep both paths visible and compare the output against the original in either case.
Before publication, record the previously approved asset and how to restore it. Test the rollback path in a non-production environment. After replacing an image, caches and downstream exports may continue serving the older file for a period; use your site's documented cache and asset-versioning behavior to verify the actual public result.
If an image is reported as misleading after release, remove or replace it according to your incident process. Preserve the evidence and review history required by policy, restrict access to it, and communicate with affected teams. Don't rely on a filename such as final-final.png to identify the version that was actually published.
Handle streaming previews carefully
Some supported image workflows can stream partial images before the final result. A partial preview can reassure a user that the job is progressing, but it isn't necessarily the final image. Label it as a preview and avoid allowing a reviewer to approve or publish it as the finished asset.
The current OpenAI guide notes that the requested number of partial images may not all arrive if the final image is ready sooner. Design the interface around the final completion event rather than waiting for an exact count of previews. Handle a disconnected client, a failed job, and a final result that arrives after the user leaves the page.
Store or discard previews according to a stated retention policy. A preview can contain source-derived information even if it is never approved. If you don't need it for troubleshooting or review, avoid retaining it longer than necessary. Ensure that a later user cannot see a previous user's preview through a shared cache or predictable URL.
Respond to errors without losing the source
Failures can happen before, during, or after generation. A source file may be missing or unsupported. The API may reject a parameter, deny access to a model, return a policy refusal, or encounter a temporary failure. The output may arrive but fail to save because the disk is full or a filename already exists.
Classify errors so the next step makes sense. A malformed mask or unsupported format needs correction, not repeated retries. An access error may require an account or project administrator to check permissions. A temporary service failure may be eligible for a bounded retry, subject to the provider's instructions and your spending policy. A policy rejection should be surfaced for review rather than treated as a network timeout.
A request that times out can leave uncertainty about whether the provider processed it. Retrying may create a second charge or candidate. Check the SDK's documented retry behavior and design your own retry policy around the operational and cost consequences. Log a request ID and status where available; avoid logging keys, raw base64, or sensitive source images.
Keep the original source intact through every failure. If the candidate can't be saved, show that the job failed rather than reporting an approval. If an image is saved but the metadata write fails, flag the record for repair rather than silently attaching an incomplete history to it.
Privacy and access controls
An image can reveal more than its subject. A product photograph might include a customer name in the background, a face in a reflection, location information in metadata, or an unreleased design. Review the source and references before upload. If the job involves a person, confirm that the intended transformation and use are authorized under your policies and applicable rules.
OpenAI's data controls documentation describes application state, abuse monitoring, available retention controls, and image-input exceptions. Review the settings applicable to your account and endpoint. Saving output locally doesn't mean the source image stayed local; it was sent to the provider for processing.
Your application may create additional copies in temporary files, object storage, logs, analytics, support tools, backups, and caches. Map those copies and define who can access them and when they are removed. Use private storage and scoped access for unapproved assets. If you use time-limited links, treat them as credentials while they remain valid.
Avoid publishing prompts or reference images automatically as part of the final asset. A prompt can contain a private campaign plan even when the finished image is public. Preserve enough information to support review and maintenance, but don't collect more than you need or keep it indefinitely by default.
Cost and throughput decisions
Each candidate consumes resources, and a review process can cost more than the generation itself. Compare the full workflow: request cost, time to first candidate, number of revisions, human review time, storage, and the cost of correcting a bad publication. A cheaper setting is only useful if it produces candidates that meet the brief often enough for your use case.
Use small, explicitly budgeted experiments when comparing models or settings. Keep the same source, prompt, and review rubric across comparisons where possible. Record the number of attempts and the number accepted. Don't calculate an “acceptance rate” from a handful of cherry-picked examples and present it as a general model benchmark.
For a multi-user service, set per-user and organization limits, cap concurrent jobs, and monitor unusual usage. Ensure rate limits work across instances if you expect a global limit. An in-memory counter on one server can help locally but won't enforce a shared limit across multiple machines. Store keys on the server and don't expose the provider credential to the browser.
The current API reference documents model-specific quality, size, output-format, and other controls. Supported options and their costs can change. Recheck the pricing page and endpoint documentation before changing defaults or promising a fixed cost to users.
Test the workflow with realistic failures
Create a small set of authorized or synthetic source images with known requirements. Include a product with fine lettering, a transparent object, a textured edge, a reflective surface, and a subject close to the image boundary if those conditions match your work. Add cases with a small mask, an inverted mask, and a reference that conflicts with the written brief.
For each case, define what must change and what must remain accurate. Have reviewers assess candidates without seeing which setting produced them when practical. Record failures in specific categories such as changed geometry, incorrect text, unwanted object, poor edge, and unsuitable crop. Keep examples that failed so a later change can be tested against them.
Test the application behavior with a mocked provider response. A successful mock can verify that your program saves a candidate under a new ID and leaves the source untouched. Error mocks can check missing image data, invalid base64, file-write failures, timeouts, and a candidate filename collision. These tests don't establish visual quality or prove real API access; use a separately budgeted live smoke test for that.
Exercise the review state as well. A candidate should not appear as approved immediately after generation. A rejected candidate should not be publishable through the normal path. A changed file should require a fresh review. Test access between users or organizations so one customer can't inspect another customer's private source or candidate.
Check the final placement
Approval in an image viewer is only one step. Place the candidate in a staging version of the actual page, card, email, or document. Inspect the desktop and mobile crops, overlays, text contrast, loading behavior, and any zoom view. The design around the image can hide a defect or make an otherwise accurate image misleading.
Confirm that the page's alternative text describes the image's role. A decorative background may use an empty alt, while a meaningful product image needs a concise description that helps someone who cannot see it. Don't use alternative text as a list of keywords. If the image communicates a material product detail, make sure that detail is also available in accessible text where appropriate.
Use an image format and dimensions suited to the destination. Keep a high-quality approved source, then create derivatives for the site. Check that compression doesn't blur labels or introduce halos around transparent edges. Record which approved source each derivative came from so a replacement can be propagated consistently.
After publishing, verify the actual public page rather than assuming the deployment used the intended file. Inspect the URL and rendered result, and check any cache behavior relevant to your site. If the wrong asset appears, follow the rollback procedure and investigate the publishing pointer before approving another candidate.
A practical approval checklist
Before an edited image goes live, confirm the following:
- The original and all references are authorized for this processing and intended use.
- The requested change and protected details are documented.
- The candidate is linked to the correct source, prompt, and settings.
- A reviewer compared the candidate with the source at useful zoom levels.
- Important text, marks, geometry, colors, and accessories were checked.
- The image was inspected in its actual crop and surrounding layout.
- A named reviewer approved the exact candidate version for the intended use.
- The published derivative can be traced back to that approved version.
- The team knows how to restore the previous approved asset.
- Retention and access rules cover sources, references, previews, and drafts.
Use a more stringent review for assets where an error could mislead customers or affect safety. For an internal mood board, a lighter process may be sufficient. The purpose of the checklist is to match the review to the consequence, not to make every image pass through the same bureaucracy.
Frequently asked questions
Can a reference image guarantee that a product stays identical?
No. It guides the model, but the result may alter shape, text, color, or other details. Compare it against the approved source and use a workflow that preserves original pixels when exact preservation is required.
Does a mask prevent changes outside the selected area?
The current OpenAI guide describes the mask as guidance and says it may not be followed with complete precision. Review the whole image, especially boundaries and important details outside the requested region.
Should I use a mask or a markup overlay?
Use the representation supported by the selected model and endpoint. A mask uses transparent areas to indicate the region for an edit. Markup is a separate transparent annotation layer that can include a circle or sketch. The current guide says not to combine the two in the same request. Neither is a guarantee of exact pixel boundaries.
Can a model's successful API response automatically approve an image?
No. A successful response means the request produced a result. Approval requires checking that result against the brief and the intended use. Keep generation, review, and publication as separate states.
What if I need an exact logo or product label?
Use an approved asset and a controlled design process to preserve or reapply it, then review the final composition. A generated approximation may look convincing while changing letters or geometry. The right process depends on the rights and accuracy requirements of the asset.
Is the Responses API better than the Image API for editing?
They support different interaction patterns. The Image API suits a single edit request; the Responses API can support a conversational, multi-turn workflow. Choose based on how people will work and how your application manages context, review, and versions. Check current documentation for model and feature support.
Can I use an edited image commercially?
The answer depends on the rights in your source and references, provider terms, contracts, and the way you use the output. Check the current terms and your organization's review process. This guide doesn't provide legal advice or guarantee rights in any image.
Sources and maintenance
- OpenAI: image generation and editing guide — editing paths, masks, markup, output options, and streaming behavior.
- OpenAI: Python Images edit reference — request parameters, model support, input constraints, and response format.
- OpenAI: image prompting guide — examples of instructions for image generation and editing.
- OpenAI: image-generation tool — image editing within a Responses API workflow.
- OpenAI: API data controls — current retention and image-input considerations.
- OpenAI API pricing — current pricing and billing information.
Recheck the cited sources when changing models, masks, markup, or output settings. The example shows a candidate-generation step; it does not claim that a specific source or result has been reviewed, approved, or published.
