AI Image API Metadata Stripping: Privacy-Safe Derivatives
Your application accepts a reference photo, creates an image, and exposes a downloadable derivative. The pixels look correct, but the file can still contain a camera serial number, a user comment, or an embedded preview. AI image API metadata stripping should be an explicit delivery policy, not an assumption that saving an image automatically removes every private field.
The practical answer is to create a fresh raster derivative, normalize orientation before discarding EXIF, and carry forward color information deliberately. This problem-solving guide implements that boundary with Python and Pillow. For applications using the GenRelay image API, the examples run after a file has reached application-controlled storage. They do not claim that a particular model emits private metadata or that GenRelay guarantees metadata removal.
What metadata should an image delivery policy remove?
Remove nonessential descriptive metadata from public derivatives while explicitly deciding how to handle orientation, color, and provenance. Metadata is information stored alongside image pixels; some fields affect display, while others describe the device, author, location, or editing history.
EXIF, the Exchangeable Image File Format metadata commonly embedded in photographs, can contain capture time and GPS coordinates. XMP, the Extensible Metadata Platform, can contain descriptive fields or editing records. PNG text chunks can carry arbitrary strings. An ICC profile, an International Color Consortium color profile, describes how pixel values should be interpreted for color display.
A useful policy distinguishes these categories:
| Category | Public derivative policy | Reason |
|---|---|---|
| GPS, serial numbers, comments, timestamps | Omit | Not needed to display the asset |
| EXIF orientation | Apply to pixels, then omit | Avoid changing the intended rotation |
| ICC color profile | Preserve validated profile or convert deliberately | Avoid unintended color shifts |
| Embedded thumbnails and editing records | Omit | May expose another version of the image |
| Provenance and licensing information | Evaluate separately | Removal can affect trust or obligations |
Do not treat privacy cleaning as permission to erase required attribution. Keep the original private when retention is lawful and necessary, and maintain a separate audit record connecting the original and its derivative. If a signed provenance manifest is present, transcoding may invalidate or remove it; disclose that processing rather than presenting the derivative as an untouched original.
Why is deleting EXIF alone insufficient?
Deleting EXIF alone does not cover every container-specific metadata channel, and deleting orientation before applying it can rotate the displayed result. A JPEG can carry additional application segments; a PNG can contain textual fields unrelated to EXIF. File formats do not share a universal metadata switch.
Avoid modifying the original in place. Decode the image, apply its orientation, create a new pixel container, and encode that container using an explicit metadata allowlist. An allowlist specifies what may survive rather than attempting to enumerate every field that must disappear.
This method also changes the encoded bytes. A SHA-256 checksum, which identifies an exact byte sequence, will differ even if the rendered subject looks unchanged. Update downstream object identifiers and caches accordingly. JPEG encoding is lossy, so use PNG for the example when avoiding another lossy encoding step matters more than file size.
For a deeper explanation of rotation handling, see the EXIF orientation guide. Normalize display geometry before deriving thumbnails, computing visual hashes, or placing the result into a layout.
How can Python create a sanitized image derivative?
Use Pillow to decode a bounded, single-frame input, apply orientation, and save a new RGB or RGBA image with an explicitly validated ICC profile. Install the dependency with python3 -m pip install Pillow, then save this snippet as sanitize_image.py.
import io
import warnings
from pathlib import Path
from PIL import Image, ImageCms, ImageOps
MAX_BYTES = 20 * 1024 * 1024
MAX_PIXELS = 16_000_000
def sanitize_image(source, destination):
source, destination = Path(source), Path(destination)
if source.resolve() == destination.resolve():
raise ValueError("Use a separate destination")
with source.open("rb") as handle:
raw = handle.read(MAX_BYTES + 1)
if not raw or len(raw) > MAX_BYTES:
raise ValueError("Input byte limit")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(io.BytesIO(raw)) as original:
if original.format not in {"JPEG", "PNG"}:
raise ValueError("Unsupported format")
if getattr(original, "n_frames", 1) != 1:
raise ValueError("Animated inputs require a separate policy")
if original.width * original.height > MAX_PIXELS:
raise ValueError("Input pixel limit")
if original.mode not in {"RGB", "RGBA", "L", "LA"}:
raise ValueError("Convert unsupported color modes separately")
icc = original.info.get("icc_profile")
if icc:
if len(icc) > 1_000_000:
raise ValueError("ICC profile too large")
ImageCms.ImageCmsProfile(io.BytesIO(icc))
oriented = ImageOps.exif_transpose(original)
mode = "RGBA" if "A" in oriented.getbands() else "RGB"
pixels = oriented.convert(mode)
clean = Image.new(mode, pixels.size)
clean.paste(pixels)
options = {"icc_profile": icc} if icc else {}
clean.save(destination, format="PNG", **options)
return clean.size
The numerical limits are example application policies, not GenRelay request limits. Restrict both compressed bytes and decoded pixels: a small compressed file can expand into a large raster. This implementation intentionally rejects animation, palette images, and CMYK inputs rather than silently choosing a conversion policy for them.
The code preserves a syntactically readable profile without certifying that the profile accurately describes the pixels. For uniform web delivery, implement a separate conversion to an approved sRGB profile, then attach that profile. Do not label unchanged wide-gamut pixels as sRGB. The image color management guide explains why those operations are different.
This helper writes to a trusted destination and does not implement atomic publication. Run it inside a restricted worker with memory, CPU, and execution-time limits; validate the result before promoting it to public storage. Keep Pillow and its native codec dependencies updated.
How do you verify that private fields are absent?
Reopen the derivative and assert both the intended display properties and the permitted metadata keys. A successful save is not sufficient evidence that your delivery policy was applied.
The following offline test creates a source JPEG containing orientation and a private description, adds a valid sRGB profile, and checks the resulting PNG. Run it in the same directory as the first snippet.
from pathlib import Path
from tempfile import TemporaryDirectory
from PIL import Image, ImageCms, PngImagePlugin
from sanitize_image import sanitize_image
with TemporaryDirectory() as folder:
folder = Path(folder)
source, output = folder / "source.jpg", folder / "public.png"
profile = ImageCms.ImageCmsProfile(
ImageCms.createProfile("sRGB")
).tobytes()
exif = Image.Exif()
exif[274] = 6 # Display rotated 90 degrees clockwise.
exif[270] = "private customer reference"
Image.new("RGB", (60, 40), "orange").save(
source, exif=exif, icc_profile=profile
)
assert sanitize_image(source, output) == (40, 60)
with Image.open(output) as result:
result.load()
assert not result.getexif()
assert result.info.get("icc_profile") == profile
assert set(result.info) <= {"icc_profile"}
text_source = folder / "text.png"
text = PngImagePlugin.PngInfo()
text.add_text("Comment", "private upload note")
Image.new("RGBA", (12, 10), (255, 0, 0, 100)).save(
text_source, pnginfo=text
)
sanitize_image(text_source, output)
with Image.open(output) as result:
result.load()
assert "Comment" not in result.info
assert result.getpixel((0, 0))[3] == 100
print("Metadata, orientation, profile, and alpha checks passed")
These tests verify the behavior demonstrated here, not every possible metadata structure. Add real fixtures covering your supported camera exports, editing tools, malformed profiles, truncated inputs, and rejection paths. For higher-assurance workflows, inspect output with an independent metadata parser too. Do not put private metadata values into routine logs while testing their removal.
How should sanitized files enter a production pipeline?
Publish a derivative only after decoding, policy validation, and ownership checks complete. Keep the source and derivative as distinct assets with distinct access rules.
- Resolve an authenticated asset identifier to private application storage.
- Record the sanitization policy version and source checksum privately.
- Decode and normalize with resource limits.
- Encode to a fresh private staging object.
- Reopen and validate format, dimensions, alpha, and allowed metadata.
- Promote the object and update the application record.
Avoid trusting a filename extension or client-supplied MIME type as proof of format. If validation fails, mark the delivery job failed without automatically repeating the paid generation step. A broken derivative pipeline and an unsuccessful model request are separate failure domains.
Metadata cleaning also does not remove information visible inside the image. Faces, addresses, reflections, license plates, and text drawn into pixels remain. A privacy review may require redaction or human approval beyond this container-level operation.
What do developers frequently ask about metadata stripping?
Does this require another paid image generation request?
No. It is local processing of an existing file. As of November 23, 2026, the supplied GenRelay prices are $0.030 for Nano Banana Pro 1K or 2K, $0.042 for 4K, and $0.014 per GPT-image-2 image. Those are generation charges, not fees charged by this Pillow function. Hosting and processing costs are separate.
Does removing metadata reduce image quality?
Removing descriptive fields alone need not change pixels, but this implementation decodes and re-encodes a derivative. PNG avoids a new lossy compression step; orientation and explicit color conversion can still change pixel arrangement or values. Compare rendered output under your chosen policy.
Can I remove every profile to make the file private?
You can choose that policy, but it can change color interpretation. ICC profiles are display information, not automatically personal data. Decide whether to preserve a validated profile or convert into an approved destination color space.
Does the code remove watermarks or guarantee anonymity?
No. It does not remove visible markings or identifying pixels and makes no anonymity guarantee. Use it as one bounded file-delivery control alongside access restrictions, retention rules, and content review.