AI image API transparency: Detect Alpha and Flatten Images
Your product-image service receives a PNG, converts it to JPEG, and publishes a thumbnail with an unexpected dark background. AI image API transparency requires an explicit delivery policy: determine whether pixels are actually transparent, preserve an alpha-capable original when appropriate, and composite onto a chosen background before exporting formats without transparency.
This tutorial implements those steps in Python after generation and download. It does not claim that GenRelay models provide transparent backgrounds on request, expose a background-removal parameter, or return a particular file format. Start with the documented GenRelay image API workflow, then process the downloaded artifact inside your application.
What does transparency mean in an image API response?
Transparency means that a pixel has an opacity value in addition to its color values. An alpha channel stores those opacity values; for an eight-bit alpha channel, zero is fully transparent and 255 is fully opaque. Intermediate values describe partial coverage or opacity, such as a soft edge.
A PNG extension alone does not establish transparency. A PNG can contain opaque RGB pixels, an RGBA image whose alpha values are all 255, or a palette whose transparency is described separately. Conversely, a checkerboard visible in a generated image may be painted into the pixels rather than representing transparency.
Inspect decoded pixels instead of trusting filenames, MIME headers, or visual previews. Distinguish three properties in your asset record: whether the source can encode transparency, whether any decoded pixels are nonopaque, and whether your product accepts that transparency. These properties answer different operational questions.
Where should alpha inspection happen in the pipeline?
Inspect alpha after safe decoding and before exporting delivery derivatives. Retain the original in private storage, create a normalized processing image, and produce separate transparent and flattened outputs when your application needs both.
A practical sequence is:
- Validate downloaded bytes, dimensions, and supported formats.
- Decode a single approved frame within resource limits.
- Resolve source color handling before compositing.
- Inspect the decoded alpha range.
- Save an alpha-preserving PNG or composite onto a configured background.
- Validate the exported files before marking the asset deliverable.
Use the existing image output validation guide for the broader file-validation boundary. A successful generation status is not sufficient evidence that an artifact is suitable for your delivery channel. The alpha-processing stage is an application concern, not a substitute for generation-status reconciliation.
How can Python detect actual transparent pixels?
Convert a supported decoded image to RGBA and inspect the extrema of its alpha channel. This also resolves palette transparency into explicit per-pixel opacity, avoiding a common mistake where checking only the image mode misses transparent palette entries.
Install Pillow with python -m pip install Pillow. The following example intentionally accepts only single-frame PNG inputs in RGB, RGBA, or palette mode. Restricting the accepted input contract makes its behavior easier to test; expand it deliberately rather than silently handling every format.
from pathlib import Path
import warnings
from PIL import Image
MAX_BYTES = 20 * 1024 * 1024
MAX_PIXELS = 16_000_000
def read_png(path):
path = Path(path)
if path.stat().st_size > MAX_BYTES:
raise ValueError("encoded image exceeds size policy")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path) as source:
if source.format != "PNG":
raise ValueError("expected decoded PNG format")
if getattr(source, "n_frames", 1) != 1:
raise ValueError("animated images require another pipeline")
if source.mode not in {"RGB", "RGBA", "P"}:
raise ValueError("unsupported source mode")
width, height = source.size
if width * height > MAX_PIXELS:
raise ValueError("decoded image exceeds pixel policy")
source.load()
return source.convert("RGBA")
def alpha_report(image):
low, high = image.getchannel("A").getextrema()
return {
"has_transparent_pixels": low < 255,
"fully_transparent": high == 0,
"alpha_min": low,
"alpha_max": high,
}
Save this block as alpha_delivery.py. The byte and pixel limits are example application policies, not GenRelay limits. Catch decoding and validation exceptions at the job boundary and quarantine the artifact instead of publishing a partially processed file.
A fully transparent result deserves separate handling: its format may be valid while its visible content is unusable. An all-opaque result is not necessarily a failure unless transparency is part of your own acceptance criteria. Do not automatically submit another paid generation just because alpha is absent.
How do you flatten transparent pixels for JPEG delivery?
Composite the RGBA image onto an explicit opaque background before converting to RGB and encoding JPEG. Calling convert("RGB") directly discards alpha without expressing how transparent edges should blend with the destination background.
Append this second block to alpha_delivery.py. It creates a fresh pixel container for the transparent derivative so source metadata is not implicitly copied. The example assumes that pixels already follow your chosen RGB color policy; it is not an ICC conversion implementation.
from PIL import Image
def write_derivatives(image, png_path, jpeg_path,
background=(255, 255, 255)):
if len(background) != 3 or any(
not isinstance(v, int) or not 0 <= v <= 255
for v in background
):
raise ValueError("background must contain three byte values")
clean = Image.new("RGBA", image.size)
clean.paste(image)
clean.save(png_path, format="PNG")
canvas = Image.new("RGBA", clean.size, (*background, 255))
flattened = Image.alpha_composite(canvas, clean).convert("RGB")
flattened.save(jpeg_path, format="JPEG", quality=90)
if __name__ == "__main__":
from tempfile import TemporaryDirectory
from pathlib import Path
with TemporaryDirectory() as folder:
folder = Path(folder)
source = folder / "source.png"
Image.new("RGBA", (8, 8), (255, 0, 0, 128)).save(source)
image = read_png(source)
assert alpha_report(image)["has_transparent_pixels"]
write_derivatives(image, folder / "alpha.png",
folder / "preview.jpg")
with Image.open(folder / "alpha.png") as output:
assert output.getpixel((0, 0))[3] == 128
with Image.open(folder / "preview.jpg") as output:
assert output.mode == "RGB"
r, g, b = output.getpixel((0, 0))
assert r > 240 and 115 <= g <= 140 and 115 <= b <= 140
print("alpha delivery tests passed")
Run python alpha_delivery.py to exercise the synthetic fixture. The test verifies preservation of half-opacity pixels and an approximately pink JPEG result over white. JPEG is lossy, so assertions allow a range instead of requiring exact RGB values. These are local processing checks, not a benchmark of any image model.
What causes dark fringes and inconsistent edge colors?
Dark fringes often come from compositing mistakes or source edge colors that were prepared against another background. Alpha alone cannot repair an edge whose color values already contain an unwanted matte.
Straight alpha stores color independently from opacity; premultiplied alpha stores color multiplied by opacity. Mixing the two conventions can produce dark or bright outlines. The Pillow RGBA path above uses its normal straight-alpha representation; external GPU buffers or specialized image libraries may use another convention. Establish that boundary explicitly when transferring pixels between systems.
Color space also affects compositing. The compact example uses Pillow's ordinary channel arithmetic rather than a specialized linear-light compositing pipeline. For demanding product photography or design workflows, define the intended compositing space and compare approved edge fixtures. Follow your color management policy before removing profiles or changing backgrounds.
Test transparent black pixels, white product edges, partially transparent shadows, and palette-based PNGs. Inspect previews over both light and dark backgrounds. A white-background thumbnail can conceal defects that become visible in a dark storefront theme.
How should transparency processing affect generation budgets?
Treat local derivative creation separately from paid generation attempts. Encoding another JPEG from a stored original is application processing; it does not itself require a new model request. Storage and compute costs still belong in your operating budget.
Using the GenRelay prices supplied for November 12, 2026, a hypothetical batch of 100 generated pictures costs $1.40 with GPT-image-2 at $0.014 per picture. At Nano Banana 2's 1K rate of $0.020, the same generation count costs $2.00. Nano Banana Pro costs $3.00 for 100 pictures at either the 1K or 2K rate of $0.030, or $4.20 at the 4K rate of $0.042.
These are generation-price calculations, not claims that any model returns transparent output or achieves a stated acceptance rate. Record rejected artifacts and paid revisions independently. If your application requires background removal, verify a documented capability or add a separately evaluated processing stage rather than promising that a prompt guarantees an alpha channel.
What do developers ask about image transparency?
Does a PNG response guarantee a transparent background?
No. Decode the image and inspect alpha values. Opaque PNGs and painted checkerboards can look like transparency-related outputs without containing nonopaque pixels.
Can I save an RGBA image directly as JPEG?
JPEG does not represent alpha transparency. Composite onto a chosen background, convert to RGB, and then encode. Keep a separate alpha-capable original when future background changes matter.
Does detecting transparency prove that background removal worked?
No. Alpha inspection verifies opacity values, not semantic segmentation quality. Product edges, holes, reflections, and shadows still need application-specific review.
Should I regenerate if my JPEG preview has the wrong background?
Usually not. If the stored original has usable alpha, rebuild the derivative locally with the correct background. Regeneration is a separate decision that can create another generation charge.