AI Image API Multi-Frame Detection: Reject Animated Inputs
Your application accepts a reference image, creates a thumbnail, and submits it to a generation workflow. A customer uploads an animated WebP, but the thumbnail displays just its opening frame. AI image API multi-frame detection prevents this silent mismatch by checking the decoded container before a still-image workflow accepts the asset.
The practical policy is simple: accept exactly one decoded frame, reject multi-frame containers, and make any frame-extraction feature explicit. This problem-solving guide implements that policy locally with Pillow, a Python image-processing library. In an application using the GenRelay image API, these checks belong to your ingestion service. They are not claims about undocumented GenRelay validation behavior or generation parameters.
What counts as a multi-frame image?
A multi-frame image is a container that exposes more than one image frame or page through its decoder. Animation is one use, but not the definition: a multi-page TIFF can contain several independent still pages without representing motion.
GIF, animated PNG, and animated WebP can represent time-based sequences. TIFF can represent document pages. A single filename extension does not establish which case you received. Some containers in an animation-capable format contain just one frame; others contain hundreds. Inspect the bytes through a supported decoder rather than classifying uploads from their filename or browser-supplied content type.
In Pillow, n_frames reports the frame count exposed by the format plugin. A plugin is the decoder implementation for a specific file format. The property is useful for routing, but discovering the count does not guarantee every frame is valid or safe to decode. A malformed later frame may still fail when accessed.
For a still-image-only service, do not decode all frames to prove they are usable. Rejecting a container as soon as its reported count exceeds one avoids unnecessary processing. Conversely, accepting a one-frame file should still require decoding that frame successfully.
Why should a still-image pipeline reject animation?
Rejecting animation makes the application's input contract match the visual asset it actually processes. Automatically using frame zero can omit the product, person, or reference pose the customer intended to submit.
This distinction matters even when the first frame looks normal. Animated PNG can include a separate default image that is not part of the animation timeline. GIF and WebP sequences can use partial-frame updates whose appearance depends on compositing. Compositing combines a frame with previous frames to construct the displayed image. Reading raw frame data without those rules can produce a misleading reference.
A useful policy table separates detection from transformation:
| Input | Still-only ingestion | Optional separate feature |
|---|---|---|
| Single-frame PNG, JPEG, or WebP | Decode and validate | Standard resizing |
| Animated GIF, PNG, or WebP | Reject with a clear message | User-selected timestamp extraction |
| Multi-page TIFF | Reject with a clear message | User-selected page extraction |
| Unsupported format | Reject | Offline conversion under a separate contract |
| Truncated or invalid container | Reject | Ask for a new upload |
Do not advertise that rejecting animation sanitizes the accepted image. Orientation, embedded metadata, color interpretation, and pixel limits remain separate responsibilities. The decompression limits guide covers the difference between compressed file size and decoded pixel allocation.
How can Python enforce a single-frame policy?
Check the file's size and decoded format, inspect its frame count, and fully load the accepted frame before returning a validation result. The following function accepts an application-controlled local file, not an arbitrary URL or user-selected filesystem path.
Install Pillow with python3 -m pip install Pillow. Run the code in a bounded worker against a private, immutable staged upload. The numeric limits below are example application policies, not provider quotas. Restrict operating-system memory and execution time as well: library checks alone cannot isolate a hostile decoder workload.
import warnings
from pathlib import Path
from PIL import Image
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 16_000_000
ALLOWED = {"JPEG", "PNG", "WEBP", "GIF", "TIFF"}
def inspect_still(path):
path = Path(path)
size = path.stat().st_size
if not 0 < size <= MAX_BYTES:
raise ValueError("File size is outside the upload policy")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path) as image:
if image.format not in ALLOWED:
raise ValueError("Unsupported decoded image format")
width, height = image.size
if width <= 0 or height <= 0:
raise ValueError("Invalid dimensions")
if width * height > MAX_PIXELS:
raise ValueError("Decoded image exceeds the pixel policy")
frames = getattr(image, "n_frames", 1)
if frames != 1:
raise ValueError("Upload one still frame or one page")
image.seek(0)
image.load()
return {
"format": image.format,
"width": width,
"height": height,
"frames": frames,
}
The format allowlist is intentional. An allowlist names the formats the application agrees to process, rather than trusting every decoder installed in the environment. TIFF is included so that a single-page TIFF can be accepted while a multi-page TIFF receives the same clear policy rejection as animation. Remove TIFF if your product does not need it.
Catch decoder exceptions at the worker boundary and return a generic invalid-upload response. Do not translate every failure into “animated image”: corruption, unsupported compression, excessive dimensions, and an actual multi-frame rejection are different diagnostic categories. Log a bounded error category internally without copying customer filenames or embedded metadata into public errors.
How do you test the policy without paid API calls?
Generate small local fixtures that differ in frame count, then assert that still images pass and multi-frame containers fail. This tests your application boundary without making a generation request or spending model credits.
Save the first snippet as still_policy.py, then run the following script alongside it. The GIF frames use different colors so the encoder does not collapse identical frames into a single image. The TIFF fixture checks that the policy covers multiple pages, not just animation.
from pathlib import Path
from tempfile import TemporaryDirectory
from PIL import Image
from still_policy import inspect_still
def must_reject(path):
try:
inspect_still(path)
except ValueError as exc:
assert "one still frame" in str(exc), str(exc)
else:
raise AssertionError("Multi-frame input was accepted")
with TemporaryDirectory() as directory:
root = Path(directory)
first = Image.new("RGB", (32, 24), "red")
second = Image.new("RGB", (32, 24), "blue")
try:
still = root / "still.png"
first.save(still)
assert inspect_still(still)["frames"] == 1
animation = root / "animation.gif"
first.save(animation, save_all=True,
append_images=[second], duration=100, loop=0)
must_reject(animation)
pages = root / "pages.tiff"
first.save(pages, save_all=True, append_images=[second])
must_reject(pages)
disguised = root / "looks-like-a-jpeg.jpg"
disguised.write_bytes(animation.read_bytes())
must_reject(disguised)
finally:
first.close()
second.close()
print("Single-frame policy tests passed")
Expand this matrix with animated WebP when your Pillow build supports WebP animation, and with animated PNG for your supported decoder version. Also test corrupt files, oversized dimensions, empty uploads, and single-frame GIF. Record the Pillow version in your build evidence: format support can depend on both Pillow and its linked native libraries.
These fixtures validate policy behavior, not the absence of decoder vulnerabilities. Keep dependencies updated and do not execute untrusted image processing inside a privileged web-server process.
Where should detection happen in the ingestion workflow?
Run detection before resizing, metadata cleaning, reference submission, or public storage. Those operations may flatten a sequence and erase the evidence that the original upload violated the still-image contract.
A reliable sequence is:
- Authenticate the upload and allocate a private staged object.
- Enforce transfer-size limits while receiving bytes.
- Close the staged file and prevent concurrent modifications.
- Inspect the decoded format, pixel dimensions, and frame count.
- Decode the single accepted frame within a resource-limited worker.
- Apply explicitly approved transformations and validate the derivative.
- Publish the derivative only after all checks succeed.
Keep validation and subsequent processing attached to the same immutable object version. Otherwise, one worker can inspect a single-frame upload while another processes replaced bytes. A private staging directory with application-generated names is a starting point; a storage system with immutable object versions makes the association more explicit.
After acceptance, the metadata stripping guide explains how to create a fresh derivative without accidentally retaining descriptive metadata. Frame-count validation does not replace that step, and metadata cleaning should not silently become animation flattening.
What does this policy change about generation costs?
Local validation does not change model unit prices, but rejecting unsupported inputs before submission can avoid unnecessary generation attempts. Calculate expected spend from submitted requests, not from files that were rejected locally.
Using the supplied GenRelay prices as of November 24, 2026, Nano Banana Pro costs $0.030 per image at 1K or 2K and $0.042 at 4K. Nano Banana 2 costs $0.020 at 1K and $0.036 at 4K. GPT-image-2 costs $0.014 per image.
For example, 100 submitted Nano Banana 2 requests at 1K total $2.00 in generation charges under that price assumption. A locally rejected animated upload is not an additional generation in that calculation. Worker compute, storage, transfer, and any submitted retries are separate costs. This arithmetic is a planning example, not a measured acceptance rate or a promise about refunds.
What do developers ask about multi-frame detection?
Is checking the file extension sufficient?
No. A GIF container can be named .jpg, and an animation-capable format can contain one frame. Inspect the decoded format and frame count from the staged bytes.
Should I automatically select the first frame?
Not under a still-only upload contract. Offer extraction as a separate, visible feature with a preview and an explicit timestamp or page selection. Never imply the entire sequence was processed.
Does n_frames == 1 prove the file is safe?
No. It establishes one aspect of the input policy. You still need a successful decode, size and pixel limits, dependency maintenance, process isolation, and derivative validation.
Is a multi-page TIFF an animated image?
Not necessarily. It may contain document pages rather than timed motion. A single-frame policy rejects it because it contains multiple images, regardless of whether playback is meaningful.
Must I regenerate an image after a policy rejection?
No. Ask the user for an accepted still image or provide an explicit extraction workflow. Resolve the input mismatch before submitting a new paid generation request.