AI image API EXIF privacy: Strip metadata before storage

Nov 9, 2026·9 min read

Your application receives an image, saves it to public object storage, and later discovers an embedded author name or location tag. AI image API EXIF privacy requires a deliberate processing step before that write, not an assumption that generated images contain nothing sensitive. This tutorial builds a local Python sanitizer and tests the storage boundary without making network requests or paid API calls.

The examples apply to your application after it receives bytes, including integrations using the GenRelay image API overview as a starting point. They do not describe a GenRelay metadata-removal feature or promise anything about provider outputs. Uploaded reference images, editing software, and intermediate processing can each introduce metadata.

What does EXIF removal protect, and what does it leave behind?

EXIF removal reduces exposure from embedded descriptive fields; it does not remove sensitive details drawn into the image itself.

EXIF, or Exchangeable Image File Format, stores fields such as capture time, camera information, orientation, and sometimes GPS coordinates. Other metadata containers include XMP, an extensible metadata format, and PNG text chunks, which can contain descriptions or application-specific notes. Removing EXIF alone is therefore narrower than producing a file without inherited descriptive metadata.

Visible content is different: an address on a parcel, a face, a screenshot username, or a watermark remains part of the pixels. Review those pixels under a separate content policy. Do not describe metadata stripping as anonymization, and do not assume that an image contains GPS data merely because it came from an API.

Provenance means information about an asset's origin and editing history. Content Credentials can include cryptographically signed provenance records. Re-encoding may discard those records or break their association with the original asset. Never remove provenance to misrepresent synthetic media as authentic photography. Keep truthful AI disclosures and use a supported provenance workflow where your publication policy requires one.

Where should sanitization sit in an image API integration?

Sanitize received bytes in a private processing boundary before saving a publishable derivative to application storage.

A derivative is a new asset produced from a source image. Distinguish it from the original in your database rather than silently replacing the source and its history. The sequence should be receive, validate, check provenance obligations, sanitize, inspect, and finally store. The image output validation guide covers checks that belong before publication.

Set separate policies for incoming reference uploads and generated results. Sanitizing a result cannot retract metadata already transmitted with a reference upload. If input privacy matters, process the reference before sending it, subject to applicable consent and provenance requirements.

Avoid logging raw image bodies, metadata dictionaries, or signed download URLs. If an original must be retained for auditing, put it in restricted storage with explicit retention and access rules. Otherwise keep it transient, accounting for temporary files, crash reports, and backup behavior. The example uses memory; that alone is not a complete retention guarantee.

How can Pillow produce a fresh raster without inherited metadata?

Decode an allowlisted format, apply EXIF orientation, convert its pixels, and paste them into a newly allocated image before encoding.

Pillow is a Python imaging library. A raster is a rectangular grid of pixels. Creating a fresh raster is important because copying or converting an existing Pillow image can retain its info dictionary. Omitting an explicit exif argument is not a sufficiently clear metadata policy on its own.

Install Pillow in your development environment with python -m pip install Pillow. Save the following as sanitize_image.py and run python sanitize_image.py. It accepts single-frame JPEG and PNG inputs and emits PNG. The limits are illustrative application policy choices, not universal safe values.

from io import BytesIO
import warnings
from PIL import Image, ImageOps, UnidentifiedImageError

MAX_BYTES = 8 * 1024 * 1024
MAX_PIXELS = 4_000_000


def sanitize_image(data: bytes) -> bytes:
    if not data or len(data) > MAX_BYTES:
        raise ValueError("Input byte limit or empty input")
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("error", Image.DecompressionBombWarning)
            with Image.open(BytesIO(data)) as source:
                if source.format not in {"JPEG", "PNG"}:
                    raise ValueError("Unsupported format")
                width, height = source.size
                if width * height > MAX_PIXELS:
                    raise ValueError("Pixel limit")
                if getattr(source, "n_frames", 1) != 1:
                    raise ValueError("Multiple frames rejected")
                source.load()
                oriented = ImageOps.exif_transpose(source)
                # Flatten transparency against an explicit white background.
                rgba = oriented.convert("RGBA")
                background = Image.new("RGBA", rgba.size, "white")
                flattened = Image.alpha_composite(background, rgba)
                rgb = flattened.convert("RGB")
                fresh = Image.new("RGB", rgb.size)
                fresh.paste(rgb)
                output = BytesIO()
                fresh.save(output, format="PNG")
                return output.getvalue()
    except (UnidentifiedImageError, OSError, SyntaxError,
            Image.DecompressionBombWarning,
            Image.DecompressionBombError) as exc:
        raise ValueError("Rejected image") from exc


def test_orientation_and_metadata():
    source = Image.new("RGB", (2, 3), "red")
    exif = Image.Exif()
    exif[274] = 6  # Rotate 90 degrees clockwise for display.
    exif[315] = "Private author"
    buffer = BytesIO()
    source.save(buffer, format="JPEG", exif=exif)
    cleaned = sanitize_image(buffer.getvalue())
    with Image.open(BytesIO(cleaned)) as result:
        result.load()
        assert result.size == (3, 2)
        assert result.mode == "RGB"
        assert not result.getexif()
        assert not result.info


if __name__ == "__main__":
    test_orientation_and_metadata()
    print("orientation and metadata test passed")

Orientation must be applied before the orientation tag disappears; otherwise a portrait image can display sideways. Transparency also needs a deliberate decision. This example composites onto white so transparent pixels do not become an unintended dark background when converted to RGB, a three-channel red, green, and blue representation.

An ICC profile describes how numerical color values map to colors. This sample does not perform color-managed conversion before dropping that profile. If color fidelity is required, add a validated profile-conversion stage, such as a carefully bounded Pillow ImageCms workflow, before creating the fresh raster. Do not promise identical color appearance from this minimal sanitizer.

How do you test that rejected images never reach storage?

Make sanitization complete successfully before calling the storage writer, then test both accepted derivatives and rejected inputs locally.

Save this second snippet as test_storage.py beside the first file and run python test_storage.py. Its temporary directory stands in for application storage. No provider endpoint, credential, or paid generation is involved. Synthetic fixtures avoid putting real personal information into the test suite.

from io import BytesIO
from pathlib import Path
from tempfile import TemporaryDirectory
from PIL import Image, PngImagePlugin
import sanitize_image as sanitizer


def store_derivative(data, destination):
    cleaned = sanitizer.sanitize_image(data)
    with destination.open("xb") as handle:
        handle.write(cleaned)


def expect_rejected(data, destination):
    try:
        store_derivative(data, destination)
    except ValueError:
        assert not destination.exists()
    else:
        raise AssertionError("Input unexpectedly accepted")


def run_tests():
    with TemporaryDirectory() as directory:
        root = Path(directory)
        source = Image.new("RGBA", (2, 2), (0, 0, 255, 0))
        metadata = PngImagePlugin.PngInfo()
        metadata.add_text("Description", "Private fixture text")
        buffer = BytesIO()
        source.save(buffer, format="PNG", pnginfo=metadata)
        store_derivative(buffer.getvalue(), root / "clean.png")
        with Image.open(root / "clean.png") as result:
            result.load()
            assert result.mode == "RGB"
            assert result.getpixel((0, 0)) == (255, 255, 255)
            assert not result.info
            assert not result.getexif()

        expect_rejected(b"not an image", root / "invalid.png")
        expect_rejected(b"", root / "empty.png")
        expect_rejected(b"x" * (sanitizer.MAX_BYTES + 1),
                        root / "oversize.png")

        original_limit = sanitizer.MAX_PIXELS
        try:
            sanitizer.MAX_PIXELS = 3
            expect_rejected(buffer.getvalue(), root / "pixels.png")
        finally:
            sanitizer.MAX_PIXELS = original_limit

        animated = BytesIO()
        frame = Image.new("RGB", (2, 2), "black")
        frame.save(animated, format="PNG", save_all=True,
                   append_images=[Image.new("RGB", (2, 2), "white")])
        expect_rejected(animated.getvalue(), root / "animated.png")

        unsupported = BytesIO()
        frame.save(unsupported, format="BMP")
        expect_rejected(unsupported.getvalue(), root / "unsupported.png")
    print("storage acceptance and six rejection cases passed")


if __name__ == "__main__":
    run_tests()

These tests check orientation dimensions, removal of fixture metadata, transparency handling, and rejection before writing. They do not prove support for every malformed image or provenance format. Extend the corpus with permitted real-world formats, rotated pixel patterns, truncated streams, and color-profile fixtures before deployment.

What limits and storage controls belong in production?

Bound resource use independently of metadata removal, and publish the derivative only after processing and policy checks finish.

Compressed byte size does not predict decoded memory use. Several image buffers coexist in this implementation, so pixel limits must reflect worker memory and concurrency. Run untrusted decoding in resource-limited workers with timeouts, maintain patched dependencies, and cap download size while streaming rather than after buffering everything.

The storage example is intentionally small: exclusive creation prevents overwriting an existing path, but a failed write can still leave a partial file. Production systems need private staging, cleanup, and a final publication step with appropriate atomicity for their storage backend. Generate object names server-side, set the emitted content type to image/png, and never derive filesystem paths directly from uploaded filenames.

Re-encoding changes bytes. Calculate the stored derivative's digest after sanitization, and keep source identity separate when retention permits; see image content hashes. A content hash identifies bytes, not consent, authorship, or safety. Store minimal transformation records and truthful origin labels without copying sensitive metadata into public database fields.

What are common questions about AI image API EXIF privacy?

The common implementation questions concern scope, orientation, provenance, and verification rather than a provider-specific switch.

Does removing EXIF remove a visible watermark?

No. A visible watermark is pixel content, and this tutorial preserves it. Do not use metadata processing to suggest that a synthetic image has a different origin.

Can I delete EXIF without applying orientation?

You can, but the displayed rotation may change. Apply orientation to the pixels first, then omit the original tag from the newly encoded derivative.

Does a fresh raster preserve Content Credentials?

Do not assume it does. Re-encoding can remove or invalidate provenance. Route assets requiring credentials through a supported provenance-preserving or re-signing process, with accurate transformation history and appropriate authorization.

Does an empty Pillow metadata dictionary prove complete privacy?

No. It verifies a limited property of the decoded output in these tests. Review visible content, application records, filenames, storage permissions, and disclosure obligations separately; use format-aware inspection where stronger assurance is required.

Related posts

Join our DiscordAI image API EXIF privacy: Strip metadata before storage — GenRelay