AI image API color management: a Python implementation
Your generated product image looks warm in a design application but washed out in a storefront thumbnail. AI image API color management starts with determining what the downloaded pixels mean, not adjusting saturation until two previews match. A missing color profile, an incorrectly assigned profile, or an export that removes the profile before conversion can each create inconsistent rendering.
This tutorial implements an application-side normalization step after downloading an image. It is not a claim that GenRelay performs ICC conversion or exposes color-management parameters. Keep your existing documented generation and download flow; the examples operate on local files and require no API endpoint or credentials.
What does color management change in an API image workflow?
Color management translates pixel values between defined color spaces so their intended appearance can be preserved within the destination's limits. A color space specifies how numeric color coordinates relate to colors; sRGB is a widely supported RGB color space for web delivery. An International Color Consortium (ICC) profile describes a device or color space in a form that color-management software can interpret.
An RGB triplet is not a complete color specification. The same numbers interpreted through different profiles can describe different colors. Assigning a profile labels existing numbers without changing them; converting between profiles calculates new numbers using the source and destination descriptions. These operations are not interchangeable.
A practical delivery policy is to convert supported, explicitly tagged RGB images to sRGB and embed the destination profile. Preserve the downloaded original separately. Conversion cannot restore colors that were already clipped, and it does not make generated brand colors match a brand specification automatically.
Where should normalization happen after generation?
Normalize after downloading and validating the image, but before making delivery derivatives or discarding source metadata. This sequence keeps the source ICC profile available when it is needed to interpret the pixels.
For a GenRelay integration using the GenRelay image API, treat the downloaded artifact as input to your own media-processing service. Do not assume that a particular model always returns a particular profile, format, or transparency mode unless its documented contract establishes that behavior.
Use this processing order:
- Validate the downloaded file's actual format, dimensions, and decoded resource requirements.
- Record whether an embedded ICC profile exists and retain the original artifact.
- Apply an explicit source-profile or untagged-image policy.
- Convert supported color channels, preserving transparency separately.
- Export a new file with the destination profile, then reopen and validate it.
The image output validation guide covers the surrounding acceptance checks. Keep Pillow's decompression-bomb protection enabled, enforce service-specific size limits, and reject unsupported inputs instead of quietly forcing every file through an RGB conversion.
How can Python convert an ICC-tagged RGB image to sRGB?
Use Pillow's ImageCms module to transform RGB channels from the embedded source profile to an sRGB destination profile. ImageCms uses Little CMS, a color-management engine. Install Pillow with python -m pip install Pillow; the installed build must support ImageCms. These examples were tested with Pillow 11.3.0 and Little CMS 2.17.
Save the following as normalize_color.py. Run it with python normalize_color.py source.png normalized.png. It deliberately accepts single-frame, 8-bit RGB and RGBA images with RGB ICC profiles. RGBA means red, green, blue, and alpha, where alpha represents opacity. Palette, grayscale, CMYK, animated, and higher-precision workflows need separate handling rather than an undocumented conversion policy.
import argparse
import io
from pathlib import Path
from PIL import Image, ImageCms
def normalize(source, destination, *, assume_srgb=False):
source, destination = Path(source), Path(destination)
if source.resolve() == destination.resolve():
raise ValueError("Keep the original; use a different output path")
if destination.exists():
raise FileExistsError(destination)
if destination.suffix.lower() != ".png":
raise ValueError("This example exports PNG")
target = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB"))
with Image.open(source) as image:
if getattr(image, "n_frames", 1) != 1:
raise ValueError("Expected a single-frame image")
if image.mode not in ("RGB", "RGBA"):
raise ValueError(f"Unsupported mode: {image.mode}")
image.load()
icc = image.info.get("icc_profile")
alpha = image.getchannel("A") if image.mode == "RGBA" else None
rgb = image.convert("RGB")
if icc:
# Invalid profiles fail here; do not silently assume sRGB.
origin = ImageCms.ImageCmsProfile(io.BytesIO(icc))
if origin.profile.xcolor_space.strip() != "RGB":
raise ValueError("Expected an RGB source profile")
converted = ImageCms.profileToProfile(
rgb, origin, target, outputMode="RGB",
renderingIntent=ImageCms.Intent.RELATIVE_COLORIMETRIC,
)
elif assume_srgb:
# Assignment under an explicit policy, not a conversion.
converted = rgb.copy()
else:
raise ValueError("Missing ICC profile; source space is unknown")
if alpha is not None:
converted.putalpha(alpha)
# Remove inherited metadata only AFTER color conversion.
converted.info.clear()
converted.save(destination, format="PNG", icc_profile=target.tobytes())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("source")
parser.add_argument("destination")
parser.add_argument("--assume-srgb", action="store_true")
args = parser.parse_args()
normalize(args.source, args.destination, assume_srgb=args.assume_srgb)
Relative colorimetric is a rendering intent that maps in-gamut colors relative to the destination white and clips out-of-gamut colors to its gamut boundary. A gamut is the range of colors a color space can represent. This explicit intent makes the policy reproducible, but wide-gamut images may lose distinctions in saturated regions when delivered as sRGB.
The script separates alpha before conversion and restores it afterward. Opacity is not a color channel and should not be transformed by an RGB profile. This example expects ordinary, non-premultiplied RGB or RGBA data; premultiplied data has color values multiplied by opacity and needs appropriate handling before color conversion.
What should happen when an image has no ICC profile?
Reject untagged images by default unless your application has documented evidence supporting a source-space assumption. A missing ICC profile does not prove sRGB, and visual inspection cannot reliably identify the original color space.
An upstream format contract or controlled export pipeline can justify interpreting untagged bytes as sRGB. If you accept that policy, run python normalize_color.py source.png normalized.png --assume-srgb. The flag leaves RGB values unchanged and attaches an sRGB profile. It does not recover an unknown source space.
Some formats carry color information outside ICC profiles, including PNG color-space chunks. This compact implementation does not interpret all such signals, so its missing-ICC error means insufficient information for this implementation, not necessarily an absence of every color declaration. Add a format-aware policy if those inputs matter. Log whether each output came from an ICC transform or an approved assumption, and never treat a malformed embedded profile as permission to assume sRGB.
How can you test profiles, alpha, and rejection locally?
Create synthetic tagged and untagged fixtures, run normalization, and inspect reopened output rather than trusting a successful save. Save this second executable snippet as test_color.py beside normalize_color.py, then run python test_color.py.
import io
import tempfile
from pathlib import Path
from PIL import Image, ImageCms
from normalize_color import normalize
def inspect(path, expected_alpha):
with Image.open(path) as image:
image.load()
assert image.mode == "RGBA"
assert image.size == (2, 2)
assert list(image.getchannel("A").getdata()) == expected_alpha
raw = image.info.get("icc_profile")
assert raw, "Destination ICC profile is missing"
profile = ImageCms.ImageCmsProfile(io.BytesIO(raw))
assert profile.profile.xcolor_space.strip() == "RGB"
assert "srgb" in ImageCms.getProfileDescription(profile).lower()
assert not image.getexif()
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
fixture = Image.new("RGBA", (2, 2))
fixture.putdata([
(230, 40, 60, 0), (20, 180, 100, 64),
(30, 80, 220, 128), (240, 230, 200, 255),
])
alpha = [0, 64, 128, 255]
srgb = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB"))
tagged, untagged = root / "tagged.png", root / "untagged.png"
fixture.save(tagged, icc_profile=srgb.tobytes())
fixture.save(untagged)
normalize(tagged, root / "converted.png")
inspect(root / "converted.png", alpha)
try:
normalize(untagged, root / "rejected.png")
except ValueError as error:
assert "Missing ICC" in str(error)
else:
raise AssertionError("Untagged input was not rejected")
assert not (root / "rejected.png").exists()
normalize(untagged, root / "assumed.png", assume_srgb=True)
inspect(root / "assumed.png", alpha)
with Image.open(root / "assumed.png") as image:
assert list(image.getdata()) == list(fixture.getdata())
invalid = root / "invalid.png"
fixture.save(invalid, icc_profile=b"not an ICC profile")
try:
normalize(invalid, root / "invalid-out.png", assume_srgb=True)
except OSError:
pass
else:
raise AssertionError("Malformed profile was accepted")
assert not (root / "invalid-out.png").exists()
print("PASS: tagged transform, alpha, profile, rejection, assumption")
The tagged fixture is already sRGB, so this tests a real profile-transform path without demonstrating a wide-gamut numerical change. For production acceptance, add a legally usable wide-gamut RGB profile, representative images, and reference outputs from a trusted color-managed application. Check transparent edges against light and dark backgrounds; alpha preservation alone does not validate compositing quality.
Does this processing change generation pricing?
These local operations add your own compute and storage costs, not another generation request. As of November 10, 2026, the supplied GenRelay generation prices are Nano Banana Pro at $0.030 per image for 1K/2K and $0.042 for 4K; Nano Banana 2 at $0.020 for 1K and $0.036 for 4K; and GPT-image-2 at $0.014 per image.
Keep generation charges separate from normalization, thumbnail creation, and artifact storage in your application accounting. Retrying a failed local conversion should reuse the downloaded original rather than regenerate the image. Do not infer unlisted resolution prices from these figures.
What do developers frequently ask about image color management?
The recurring questions concern profile assignment, privacy, transparency, and display differences. These distinctions help prevent normalization from hiding an input problem.
Is Pillow's convert("RGB") enough to convert to sRGB?
No. It changes the image mode, not its ICC-defined color interpretation. In this tutorial it extracts RGB channels before ImageCms performs the profile transform.
Should I remove metadata before converting?
No. Preserve the source ICC profile until conversion finishes, then apply your metadata policy and embed the destination profile. EXIF, the Exchangeable Image File Format metadata used for camera and other descriptive fields, is separate from the destination ICC profile. See the EXIF privacy guide for related cleanup considerations.
Can I export the transparent result as JPEG?
Not directly with preserved transparency. JPEG lacks an alpha channel. Choose an explicit background and a tested compositing policy, then export an RGB image with its destination profile. Flattening changes the delivered pixels and deserves its own tests.
Will sRGB make every screen look identical?
No. Display calibration, viewing conditions, browser behavior, and display capabilities still affect appearance. Tagged sRGB removes one common source of ambiguity; it cannot guarantee identical rendering across devices.