AI Image API Decompression Limits: Bound Decoding Resources
Your image worker downloads a small file, opens it for a thumbnail, and suddenly exhausts its memory allowance. AI image API decompression limits address this mismatch: compressed download size does not describe the resources needed to decode an image. A production integration should constrain bytes, dimensions, total pixels, frame count, execution time, and worker memory separately.
This guide covers application-owned processing after a generation finishes through the GenRelay image API. The limits below are illustrative application policies, not GenRelay service quotas or promises about model outputs. They apply to generated files, user references, and stored assets that enter the same image-processing pipeline.
Why can a small image file require substantial memory?
A compressed image can expand into a much larger pixel buffer during decoding. Decompression is the process of reconstructing image samples from their encoded representation; decoding may also allocate temporary buffers, color-conversion results, and resized copies.
An RGB buffer typically stores three samples per pixel, while RGBA includes an additional transparency sample. For an eight-bit RGBA image measuring 4,096 by 4,096 pixels, the primary pixel buffer alone is 67,108,864 bytes, approximately 64 MiB. That calculation excludes decoder state, Python objects, temporary copies, and operating-system overhead.
A decompression bomb is an encoded file whose expansion demands disproportionate resources. Not every large image is malicious. An accidental oversized source or unexpected multi-frame format can create the same operational failure. Treat resource limits as an availability control rather than an accusation about the source.
Download size limits remain necessary, but they solve a different problem. A file can satisfy a byte limit and still exceed your pixel budget. Conversely, an acceptable high-detail image can have a large compressed size without excessive dimensions.
Which limits should an image-processing service enforce?
An image-processing service should enforce multiple independent limits before and during full decoding. Do not express the entire policy as a single maximum file size.
| Boundary | Example application policy | Failure addressed |
|---|---|---|
| Encoded bytes | 20 MiB per staged file | Excessive download and storage |
| Width and height | No side above 8,192 pixels | Extreme dimensions |
| Total pixels | At most 20 million | Large decoded buffers |
| Frames | Exactly one for a static-image route | Animated or multi-page inputs |
| Accepted formats | JPEG, PNG, WebP | Unexpected decoder paths |
| Worker runtime | Supervisor-enforced deadline | Long or stalled processing |
| Worker memory | Container or process-group limit | Decoder memory exhaustion |
These numbers are examples for a static web-image pipeline, not universal recommendations. Benchmark your real accepted dimensions and library versions before setting production limits. Some legitimate workflows need larger originals; route those to a separate processing class rather than increasing every worker's allowance.
Use a streaming download limit as bytes arrive, then check the staged file again. Ignore filename extensions when identifying the actual image format. If your application fetches remote results, restrict allowed destinations and redirects in the downloader; a decoder cannot enforce network access policy.
How can Python reject oversized files before full decoding?
Python can inspect the header and enforce a local policy before explicitly loading pixels, while treating Pillow's decompression warnings as failures. Pillow is a Python imaging library; its initial image opening is lazy for many formats, but header parsing itself still belongs inside a restricted worker.
Install a current, patched Pillow release. Save this example as image_guard.py and run it against a staged local file:
import warnings
from pathlib import Path
from PIL import Image
MAX_BYTES = 20 * 1024 * 1024
MAX_SIDE = 8192
MAX_PIXELS = 20_000_000
ALLOWED = {"JPEG", "PNG", "WEBP"}
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
def inspect_static(path):
path = Path(path)
if not 0 < path.stat().st_size <= MAX_BYTES:
raise ValueError("encoded byte limit")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path) as image:
width, height = image.size
if image.format not in ALLOWED:
raise ValueError("unsupported format")
if not (0 < width <= MAX_SIDE and 0 < height <= MAX_SIDE):
raise ValueError("dimension limit")
if width * height > MAX_PIXELS:
raise ValueError("pixel limit")
if getattr(image, "n_frames", 1) != 1:
raise ValueError("static images required")
result = {
"format": image.format,
"width": width,
"height": height,
}
image.verify()
return result
if __name__ == "__main__":
import sys
print(inspect_static(sys.argv[1]))
The explicit pixel comparison matters because warning thresholds and application requirements are not the same contract. verify() checks structural integrity where the format implementation supports it; it does not prove that every pixel can be decoded successfully. Reopen the staged file for a full load() inside the same resource-isolated processing environment before accepting it for delivery.
Keep the staged file immutable between inspection and decoding. Otherwise, another process could replace an inspected file with different bytes. See the image output validation guide for the distinction between identification, structural checking, decoding, and publication.
How do you test the policy without a dangerous fixture?
You can exercise rejection paths with tiny synthetic files and temporarily reduced limits. There is no need to construct a genuinely enormous image to test the explicit pixel check.
The following test imports the previous module, writes ordinary fixtures, and lowers the application pixel budget for one assertion. Run it in a separate test process so that changes to module settings do not affect a shared production worker.
from pathlib import Path
from tempfile import TemporaryDirectory
from PIL import Image
import image_guard
with TemporaryDirectory() as directory:
root = Path(directory)
small = root / "small.png"
Image.new("RGB", (32, 32), "white").save(small)
assert image_guard.inspect_static(small)["width"] == 32
oversized = root / "oversized.png"
Image.new("RGB", (40, 40), "white").save(oversized)
image_guard.MAX_PIXELS = 1500
try:
image_guard.inspect_static(oversized)
except ValueError as exc:
assert str(exc) == "pixel limit"
else:
raise AssertionError("pixel limit was not enforced")
broken = root / "broken.png"
broken.write_bytes(b"not an image")
try:
image_guard.inspect_static(broken)
except OSError:
pass
else:
raise AssertionError("invalid file was accepted")
print("image policy checks passed")
Add tests for animated WebP or PNG if those decoders are enabled, truncated files, unsupported formats, and dimensions just below and above your limits. Also test that rejected objects never receive public delivery URLs. A successful unit test checks policy logic; it does not establish resilience against every decoder vulnerability.
Where should resource isolation and retry decisions live?
Resource isolation should be enforced by the worker supervisor, not just by checks inside the image library. A supervisor is the component that starts, limits, observes, and terminates a processing worker.
Use a patched decoder in a short-lived process or container with restricted filesystem access, no unnecessary network connectivity, memory limits, and a runtime deadline. An HTTP request timeout is not a decoder CPU deadline. A Python thread timeout may stop waiting without stopping the native decoder.
Record distinct outcomes: unsupported format, policy rejection, decode failure, worker timeout, and memory termination. Persist the generation job identifier and the staged asset's internal identifier without logging private prompts or credentials.
Retry a temporary storage read when appropriate, but do not repeatedly decode the same resource-exhausting file. Quarantine the object and route it for review. A delivery-processing failure does not mean the paid generation failed, and starting another generation should require a separate product and budget decision.
How do decompression limits affect generation costs?
Decompression limits protect processing resources but do not change the generation price. As of November 15, 2026, the supplied GenRelay prices are Nano Banana Pro at $0.030 per 1K or 2K image and $0.042 per 4K image; Nano Banana 2 at $0.020 per 1K image and $0.036 per 4K image; and GPT-image-2 at $0.014 per picture.
For example, 1,000 Nano Banana Pro 2K generations total $30 in generation charges. If ten resulting assets are rejected by your application, that does not imply ten refunds. Any replacement generations add their own charges; local inspection, decoding, storage, and delivery have separate infrastructure costs. Check the current pricing page before changing a production budget.
Choose generation resolution for the intended output, and choose decoding limits for the largest legitimate returned file your application supports. Marketing labels such as 1K or 4K are not a substitute for inspecting actual dimensions.
What questions do developers ask about image decompression limits?
Does Pillow's pixel warning replace a worker memory limit?
No. It provides a useful signal, but peak memory depends on image mode, decoder behavior, and transformations. Enforce memory limits outside the decoder as well.
Can I accept an image after checking its dimensions?
Not yet. Dimensions are one acceptance condition. Verify the encoded structure where supported, perform bounded full decoding, and validate the intended delivery derivative before publication.
Should a rejected file trigger another paid API request?
Not automatically. Preserve the original generation record, classify the processing failure, and require an explicit replacement policy with a budget check.
Can generated images be treated as trusted files?
No. A successful generation response establishes neither decoder safety nor suitability for your application. Apply the same resource and delivery checks to every file entering the processing pipeline.