AI image API compression: JPEG and WebP Byte Budgets
Your application has an approved generated image, but its PNG file exceeds a storefront's upload limit. AI image API compression should turn that existing asset into a smaller delivery file without paying for another generation or silently damaging product labels. The practical approach is to encode locally, measure actual bytes, and reject outputs that fail either size or visual requirements.
This API tutorial begins after your application downloads a result from the GenRelay image API. Everything below runs application-side with Pillow, a Python image-processing library. No example assumes a provider supports JPEG quality, WebP output, or a generation-time compression parameter.
What does compressing an already-generated image change?
Compression changes the encoded file representation; it does not necessarily change pixel dimensions or generation cost. Lossy compression discards some image information to reduce file size. Lossless compression preserves decoded pixel values, although its savings depend on image content.
JPEG and lossy WebP can introduce artifacts: visible changes such as softened lettering, edge halos, or blocks in textured regions. A quality setting controls an encoder's trade-off, not a standardized visual score. JPEG quality 80 and WebP quality 80 are not equivalent guarantees.
Keep the approved original immutable. Build each delivery variant from that original rather than repeatedly recompressing previous exports. Record the original identifier, encoder version, format, quality, background policy, dimensions, and output byte count so a derivative can be reproduced and reviewed.
Should you choose JPEG or WebP for delivery?
Choose JPEG for opaque assets when compatibility is the priority, and evaluate WebP when your delivery consumers support it or require transparency. Actual file size depends on the image; measure both rather than assuming one format always wins.
| Requirement | JPEG | WebP in this tutorial |
|---|---|---|
| Transparent background | Must composite onto an opaque background | Preserves alpha |
| Photographic content | Test for texture and gradient damage | Test for texture and gradient damage |
| Small labels or interface text | Inspect colored edges closely | Inspect lettering and contrast closely |
| Encoder policy | RGB, no chroma subsampling | Lossy color with alpha retained |
Alpha is the per-pixel opacity channel. Compositing combines a transparent foreground with a chosen background; simply discarding alpha is not equivalent. Chroma subsampling stores color at a lower spatial resolution than brightness. The JPEG example disables it to reduce color-edge damage, potentially increasing file size.
Resize before encoding when the placement needs fewer pixels. Follow the AI image API resizing tutorial for composition-preserving size changes. Compression and resizing solve different constraints; neither can recover missing detail.
How do you encode JPEG and WebP safely with Pillow?
Load a constrained source, honor orientation, and apply explicit alpha and color policies before encoding. The script below accepts single-frame RGB or RGBA PNG, JPEG, and WebP files and deliberately rejects embedded ICC color profiles. An ICC profile describes how numerical color values map to colors; removing that profile is not a color conversion.
Normalize profiled assets through a tested color-managed pipeline first. This example assumes accepted unprofiled RGB values already represent your application's intended sRGB space, a common web color space. It does not validate that assumption from pixels.
Install with python3 -m pip install Pillow, then save this as compress_image.py. WebP requires a Pillow build with WebP support. The limits are example application policies, not API limits.
import argparse
from io import BytesIO
from pathlib import Path
import warnings
from PIL import Image, ImageOps, features
MAX_BYTES = 20 * 1024 * 1024
MAX_PIXELS = 16_000_000
def load_source(path):
path = Path(path)
if not 0 < path.stat().st_size <= MAX_BYTES:
raise ValueError("source byte limit")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path) as source:
if source.format not in {"PNG", "JPEG", "WEBP"}:
raise ValueError("unsupported source format")
if getattr(source, "n_frames", 1) != 1:
raise ValueError("single-frame source required")
if source.mode not in {"RGB", "RGBA"}:
raise ValueError("RGB or RGBA source required")
if source.info.get("icc_profile"):
raise ValueError("normalize ICC color profile first")
if source.width * source.height > MAX_PIXELS:
raise ValueError("source pixel limit")
source.load()
oriented = ImageOps.exif_transpose(source)
# New image avoids inheriting source metadata.
clean = Image.new("RGBA", oriented.size)
clean.paste(oriented.convert("RGBA"))
return clean
def encode(image, fmt, quality):
if fmt not in {"JPEG", "WEBP"} or not 1 <= quality <= 95:
raise ValueError("invalid format or quality")
output = BytesIO()
if fmt == "JPEG":
background = Image.new("RGBA", image.size, "white")
pixels = Image.alpha_composite(background, image).convert("RGB")
pixels.save(output, "JPEG", quality=quality,
subsampling=0, optimize=True)
else:
if not features.check("webp"):
raise RuntimeError("Pillow WebP support required")
image.save(output, "WEBP", quality=quality, method=6)
return output.getvalue()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("source")
parser.add_argument("output")
parser.add_argument("--format", choices=["JPEG", "WEBP"], required=True)
parser.add_argument("--quality", type=int, default=85)
args = parser.parse_args()
if Path(args.source).resolve() == Path(args.output).resolve():
parser.error("preserve the source: choose a different output path")
data = encode(load_source(args.source), args.format, args.quality)
Path(args.output).write_bytes(data)
print(f"{args.format}: {len(data)} bytes")
Run python3 compress_image.py original.png delivery.jpg --format JPEG --quality 85, or substitute delivery.webp --format WEBP. The format argument determines the encoding; use a matching filename extension and HTTP content type when serving the result.
Resolve authorized asset identifiers rather than exposing arbitrary paths through a public endpoint. Keep inputs immutable during processing, patch Pillow, and bound worker memory, execution time, and concurrency. Decoded pixel limits do not replace process-level resource limits.
How do you enforce a byte budget without hiding failures?
Encode a finite quality ladder, accept the first candidate within budget, and fail explicitly when none fits. A byte budget is the maximum encoded file size your application permits. Here, 120,000 bytes means exactly that, not 120 KiB; one KiB is 1,024 bytes.
Save this second script as budget_image.py beside the first. It tests candidates from higher to lower quality without assuming file size is strictly monotonic. Each candidate is encoded from the same source pixels, not the previous candidate.
import argparse
from pathlib import Path
from compress_image import load_source, encode
QUALITIES = (90, 85, 80, 75, 70, 65, 60)
def within_budget(image, fmt, budget):
if budget < 1:
raise ValueError("budget must be positive")
attempts = []
for quality in QUALITIES:
data = encode(image, fmt, quality)
attempts.append((quality, len(data)))
if len(data) <= budget:
return data, quality, attempts
raise ValueError(f"budget not met; quality/bytes: {attempts}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("source")
parser.add_argument("output")
parser.add_argument("--format", choices=["JPEG", "WEBP"], required=True)
parser.add_argument("--max-bytes", type=int, required=True)
args = parser.parse_args()
if Path(args.source).resolve() == Path(args.output).resolve():
parser.error("preserve the source: choose a different output path")
data, quality, attempts = within_budget(
load_source(args.source), args.format, args.max_bytes
)
Path(args.output).write_bytes(data)
print(f"quality={quality}, bytes={len(data)}, attempts={attempts}")
Use python3 budget_image.py original.png budget.webp --format WEBP --max-bytes 120000. Failure raises an error before writing a new output. An older file at that path is not removed, so production jobs should use fresh staging paths and publish after validation.
The floor of 60 is a sample policy, not a universal quality threshold. If no candidate fits, reduce dimensions under an approved layout policy, adjust the budget, or request human review. Do not silently accept unlimited degradation. Bound total candidate encodes because a quality search multiplies CPU work.
How should you check whether compression damaged the image?
Inspect decoded output against the source at identical dimensions, using the intended display background. Passing a byte limit demonstrates size compliance, not visual acceptance.
- Reopen each export and confirm its format and dimensions.
- For JPEG, compare with the source composited onto the same white background.
- For transparent WebP, inspect on light and dark backgrounds for edge halos.
- Review fine lettering, gradients, hair, fabric, and product outlines at 100% zoom and at delivery size.
- Reject illegible labels or altered product details even when the file meets its budget.
Synthetic fixtures can verify byte enforcement, transparency handling, orientation, and explicit failure paths without a paid generation. They do not establish perceptual quality on real customer imagery. Maintain an approved fixture set with representative content, and recheck outputs after encoder upgrades; encoded bytes can change between library versions.
Does local compression reduce image generation charges?
Local compression avoids an additional generation request, but it does not retroactively lower the charge for an existing image. Processing, storage, and network delivery remain separate costs. GenRelay uses prepaid balance and usage-based billing, not subscriptions.
As of November 14, 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. Check current pricing before estimating a production workload.
For example, 100 GPT-image-2 generations cost $1.40 at that rate. Creating JPEG and WebP derivatives from those originals does not itself add model-generation charges. Measure actual output bytes and delivered traffic before estimating delivery savings; no fixed compression ratio applies to every generated image.
What do developers ask about AI image API compression?
These questions separate local encoding behavior from generation capabilities.
Can I set JPEG quality in every image generation request?
No. Support depends on the documented model and endpoint. These examples operate after download and make no claim about provider output parameters.
Will WebP always be smaller than JPEG?
No. Compare actual encoded sizes under acceptable visual quality. Different quality scales, image content, and transparency requirements can change the result.
Can JPEG preserve transparent product backgrounds?
No. JPEG needs an opaque background. Composite intentionally, or use an alpha-capable format such as WebP when your consumers support it.
Why does a file still exceed the budget at quality 60?
Dimensions and image complexity also affect size. The script rejects that output; it does not reduce dimensions automatically or certify lower quality as acceptable.