AI Image API File Format Detection: Validate Before Storage

Nov 25, 2026·8 min read

Your image worker downloads result.jpg, but the bytes contain a PNG. AI image API file format detection should identify the decoded format before your application chooses a storage suffix, a response Content-Type, or a processing pipeline. A filename and an HTTP header describe what a sender claims; neither demonstrates that the file is a valid image.

This tutorial adds a local validation stage after your application has obtained an image through the GenRelay image API. It does not introduce generation parameters or assume a particular provider response structure. The examples use Python 3 and Pillow, operate on application-owned files, and make no paid API calls. Install Pillow in an isolated environment with python3 -m pip install Pillow, then pin the tested version in your deployment lockfile.

What should determine an image's format?

A recognized decoder should determine the processing format, while extensions and MIME headers remain diagnostic inputs. MIME, short for Multipurpose Internet Mail Extensions, supplies media labels such as image/png that HTTP also uses to describe response bodies.

Three signals can disagree:

Signal Example Application treatment
Filename suffix .jpg Untrusted naming hint
Declared Content-Type image/jpeg Untrusted transport hint
Decoder identification PNG Candidate format requiring further validation

A file signature is a sequence of bytes associated with a format. Checking a signature can reject obvious mistakes cheaply, but recognizing the PNG signature does not prove that subsequent chunks or pixel data are intact. Likewise, a decoder identifying JPEG before loading pixels does not prove the complete image can be decoded.

Treat format detection and content validation as separate steps. First recognize a permitted format, then verify structure and decode within resource limits. Finally create a fresh delivery derivative when your product requires a controlled output format. None of these steps establishes that the depicted content is suitable for a user; that requires a separate moderation policy.

How do you detect and validate formats with Pillow?

Use a narrow format allowlist, verify the file, and reopen it for a complete pixel decode before accepting it. An allowlist is an explicit collection of permitted values; it is easier to audit than a rule accepting every format installed on a worker.

Save this executable example as detect_image.py. Its limits are illustrative application policy, not GenRelay quotas. It accepts static JPEG, PNG, and WebP files and rejects animated or multi-page inputs. Run it against a private local file that no other process can modify during inspection.

import json
import warnings
from pathlib import Path
from PIL import Image

FORMATS = {
    "JPEG": (".jpg", "image/jpeg"),
    "PNG": (".png", "image/png"),
    "WEBP": (".webp", "image/webp"),
}
MAX_BYTES = 20 * 1024 * 1024
MAX_PIXELS = 16_000_000

def inspect_image(path):
    path = Path(path)
    if not 0 < path.stat().st_size <= MAX_BYTES:
        raise ValueError("Encoded size outside application policy")
    with warnings.catch_warnings():
        warnings.simplefilter("error", Image.DecompressionBombWarning)
        with Image.open(path) as image:
            fmt = image.format
            if fmt not in FORMATS:
                raise ValueError("Unsupported decoded format")
            if getattr(image, "n_frames", 1) != 1:
                raise ValueError("Expected a single-frame image")
            width, height = image.size
            if width <= 0 or height <= 0 or width * height > MAX_PIXELS:
                raise ValueError("Pixel count outside application policy")
            image.verify()
        with Image.open(path) as image:
            if image.format != fmt or image.size != (width, height):
                raise ValueError("File changed during validation")
            image.load()
    suffix, mime = FORMATS[fmt]
    return {"format": fmt, "width": width, "height": height,
            "suffix": suffix, "content_type": mime}

if __name__ == "__main__":
    import sys
    print(json.dumps(inspect_image(sys.argv[1]), indent=2))

verify() checks integrity without producing a usable loaded image; reopening is intentional. load() then forces decoding rather than leaving a lazy decoder attached to a file. Reject decoder exceptions at your worker boundary and record a sanitized failure category. Do not convert a malformed input into an accepted result by globally enabling truncated-image loading.

This code is not a sandbox. Encoded-byte and pixel limits do not bound every decoder's memory or execution time. Run processing in a constrained worker with updated libraries, restricted filesystem access, and process-level deadlines. For a deeper explanation of animated inputs, see the multi-frame detection guide.

How do you create a delivery file with trustworthy naming?

Choose the delivery encoding explicitly and derive the file suffix and response media type from that encoding. Do not rename PNG bytes to .jpg and expect the operation to convert the image.

The following second snippet imports the inspector and creates a fresh PNG derivative. PNG preserves an alpha channel, meaning the transparency values attached to pixels. The example normalizes EXIF orientation but deliberately rejects embedded ICC color profiles: ICC profiles describe color interpretation, and silently discarding one can change appearance. Production systems that accept such files should first perform a tested color conversion.

from pathlib import Path
from PIL import Image, ImageOps
from detect_image import inspect_image

def write_delivery_png(source, destination):
    source, destination = Path(source), Path(destination)
    if destination.suffix.lower() != ".png":
        raise ValueError("PNG destination must use .png")
    if source.resolve() == destination.resolve():
        raise ValueError("Keep source and derivative separate")
    inspect_image(source)
    with Image.open(source) as image:
        if image.info.get("icc_profile"):
            raise ValueError("Color conversion required before delivery")
        oriented = ImageOps.exif_transpose(image)
        rgba = oriented.convert("RGBA")
        clean = Image.new("RGBA", rgba.size)
        clean.paste(rgba, (0, 0))
        clean.save(destination, format="PNG")
    result = inspect_image(destination)
    if result["format"] != "PNG":
        raise ValueError("Unexpected derivative format")
    return result

if __name__ == "__main__":
    import sys
    print(write_delivery_png(sys.argv[1], sys.argv[2]))

Create the destination in a private staging directory with a unique application-generated name. Publish its object reference after validation, not while encoding is in progress. The fresh image avoids copying arbitrary source metadata; preserve the original separately according to your retention policy. This transformation does not promise removal of visible marks or establish content provenance.

For browser delivery, set Content-Type: image/png from your stored derivative record, add X-Content-Type-Options: nosniff, and keep authorization independent of filenames. A permitted image format does not make an asset public or grant another tenant access.

How should mismatches and unsupported files be handled?

Record mismatches for diagnosis, but make acceptance depend on your validated-format policy rather than a cosmetic naming discrepancy. A valid PNG named .jpg may be accepted and stored under a corrected application-owned name. A payload containing HTML or an unsupported format must be rejected even when its header says image/png.

Use stable internal outcomes such as accepted_png, unsupported_format, decode_failure, multi_frame, and resource_limit. Avoid writing raw provider URLs, credentials, or private prompts into logs. Correlate the outcome with your own generation attempt identifier.

Do not automatically submit a replacement generation whenever format validation fails. First retain the original diagnostic context and decide whether the problem is a damaged download, unsupported encoding, or genuine generation failure. Reprocessing a saved valid source is different from paying for another generated image. The output validation guide explains where these checks fit before storage and delivery.

What does format validation change about image costs?

Local validation changes your processing and storage costs, not the quoted generation price. Using the supplied GenRelay prices as of November 25, 2026, the following workload arithmetic excludes retries, application compute, storage, and delivery traffic.

Model and configuration Generation price 1,000 images
Nano Banana Pro 1K or 2K $0.030/image $30.00
Nano Banana Pro 4K $0.042/image $42.00
Nano Banana 2 1K $0.020/image $20.00
Nano Banana 2 4K $0.036/image $36.00
GPT-image-2 $0.014/image $14.00

These prices do not establish which file encoding or dimensions a particular request returns. Verify the actual result. If ten saved images need a new delivery encoding, re-encode those files locally rather than assuming ten replacement generations are necessary. Encoding a delivery PNG does not upgrade its resolution or change its model provenance.

How can you test the validator before deployment?

Use controlled fixtures covering mislabeled names, malformed bytes, unsupported formats, transparency, and multi-frame inputs. Generate a small PNG, save it with a .jpg suffix, and assert the inspector reports PNG with image/png. Repeat with a genuine JPEG carrying a .png suffix. The decoder result should win in both cases.

Add a truncated PNG and a text file named .jpg; both should fail. Include a static GIF to test the format allowlist and an animated PNG or WebP to test the single-frame policy. Verify that a transparent PNG retains alpha after derivative encoding. Test an over-limit fixture in an isolated worker rather than creating a huge decode inside your ordinary test runner.

For every accepted derivative, reopen the saved file and assert format, geometry, and policy compliance. Passing the encoder call is not sufficient evidence that the delivery artifact is correct.

What do developers frequently ask?

Is an HTTP Content-Type enough to validate an image?

No. It is a sender-provided label. Recognize the bytes with a permitted decoder, verify structure, and fully decode under application resource limits.

Does changing a filename extension convert an image?

No. Conversion requires decoding and encoding. Store a suffix and media type matching the actual saved encoding.

Should every extension mismatch fail the job?

Not necessarily. A valid permitted image can be renamed safely within application storage. Treat unsupported or invalid bytes as failures regardless of their extension.

Does successful format detection make a file safe to serve?

No. You still need resource isolation, authorization, appropriate HTTP headers, content policy checks, and validation of the completed delivery derivative.

Related posts

Join our DiscordAI Image API File Format Detection: Validate Before Storage — GenRelay