AI image API resizing: Fit, Crop, and Protect Product Details
Your application needs a square catalog tile and a landscape preview from the same generated product image. AI image API resizing should create those delivery derivatives from an approved original, not submit a fresh paid generation for every placement. The engineering decision is whether to preserve the complete composition, fill a fixed rectangle, or reject a source that cannot support the requested dimensions.
This tutorial implements application-side resizing with Python and Pillow, an image decoding and processing library. It starts after you have downloaded and validated a result from the GenRelay image API. The examples do not introduce generation parameters or promise that every model supports every output size.
What is the difference between generation resolution and delivery size?
Generation resolution describes the model output configuration, while delivery size describes the dimensions of an asset your application serves. A 1K pricing tier is not a promise that every result is a particular width and height; inspect the actual decoded dimensions and the selected model's documentation.
A derivative is a new file created from an existing asset through local processing. Creating a thumbnail requires processing and storage resources, but it does not itself create another generation request. Keep an immutable approved original so future layout changes do not force your application to resample an already compressed thumbnail.
Store the source asset identifier, source hash, processing policy version, target dimensions, and export format with each derivative. A hash is a digest of file bytes used to identify an exact artifact. This record makes it possible to explain which original produced a customer-visible image and to rebuild derivatives when your processing policy changes.
Should you fit the full image or crop to fill a rectangle?
Use fit when the entire subject must remain visible, and crop only when the product explicitly accepts losing content at the edges. Aspect ratio is the relationship between an image's width and height; mismatched source and target ratios require padding, cropping, or distortion.
| Strategy | What remains unchanged | What changes | Suitable application contract |
|---|---|---|---|
| Fit with padding | Complete composition and proportions | Empty space around the image | Product catalogs and document previews |
| Crop to fill | Proportions and target dimensions | Some edge content disappears | Reviewed editorial thumbnails |
| Stretch | Target dimensions only | Subject proportions | Usually unsuitable for product images |
| Reject | Original bytes | No derivative is produced | Layouts requiring approved composition |
A center crop does not understand the subject. It can remove a handle, label, face, or legally required text. Treat automatic cropping as a layout operation rather than semantic approval. If your product uses focal-point coordinates, validate and version them as application metadata instead of assuming a generation response contains them.
How do you prepare a source before resizing?
Decode under explicit resource limits, apply the recorded orientation, and establish color and transparency policies before exporting. EXIF orientation is metadata that tells a viewer how stored pixels should be rotated or mirrored for display; ignoring it can turn a portrait photograph sideways.
The example accepts a narrow contract: single-frame RGB or RGBA PNG and JPEG files. It rejects embedded ICC color profiles rather than pretending that dropping a profile converts colors. Route those files through your color management policy first. It also rejects other pixel modes deliberately; expanding format support requires separate tests.
Install Pillow with python3 -m pip install Pillow, then save this block as resize_delivery.py. The limits are example application policies, not GenRelay service limits. The input directory must be private and the selected file immutable while it is being processed.
from pathlib import Path
import warnings
from PIL import Image, ImageOps
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("encoded byte limit")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path) as source:
if source.format not in {"PNG", "JPEG"}:
raise ValueError("unsupported file format")
if getattr(source, "n_frames", 1) != 1:
raise ValueError("single-frame source required")
if source.mode not in {"RGB", "RGBA"}:
raise ValueError("unsupported pixel mode")
if source.info.get("icc_profile"):
raise ValueError("normalize color profile first")
if source.width * source.height > MAX_PIXELS:
raise ValueError("decoded pixel limit")
source.load()
oriented = ImageOps.exif_transpose(source)
return oriented.convert("RGBA")
Do not expose arbitrary filesystem paths through a public resize endpoint. Resolve application-owned asset identifiers after tenant authorization. Run decoding in a constrained worker with bounded memory and CPU resources, keep the decoder patched, and quarantine decoding failures rather than returning partially processed output.
How can Python produce fixed-size thumbnails without stretching?
Calculate a proportional scale, reject unwanted upscaling, and either composite the fitted image onto a canvas or crop the resized image. Upscaling means increasing pixel dimensions; it cannot recover detail absent from the original.
Append the following block to resize_delivery.py. The crop implementation resamples alpha-bearing pixels through Pillow's premultiplied representation before converting back to RGBA. Premultiplied alpha stores color multiplied by opacity, which helps prevent invisible pixel colors from contaminating resized edges. The final file is explicitly composited onto white and saved as RGB PNG for deterministic tests.
import math
def derivative(source, size, strategy="fit", allow_upscale=False):
if (len(size) != 2 or any(type(v) is not int or v < 1
for v in size)):
raise ValueError("positive integer dimensions required")
width, height = size
if width * height > MAX_PIXELS:
raise ValueError("output pixel limit")
if strategy not in {"fit", "crop"}:
raise ValueError("unknown resize strategy")
ratios = (width / source.width, height / source.height)
scale = min(ratios) if strategy == "fit" else max(ratios)
if scale > 1 and not allow_upscale:
raise ValueError("source too small for policy")
rounding = math.floor if strategy == "fit" else math.ceil
resized_size = tuple(max(1, rounding(v * scale))
for v in source.size)
pixels = source.convert("RGBa").resize(
resized_size, Image.Resampling.LANCZOS
).convert("RGBA")
if strategy == "crop":
left = (pixels.width - width) // 2
top = (pixels.height - height) // 2
pixels = pixels.crop((left, top, left + width, top + height))
canvas = Image.new("RGBA", size, (255, 255, 255, 255))
position = ((width - pixels.width) // 2,
(height - pixels.height) // 2)
canvas.alpha_composite(pixels, dest=position)
output = Image.new("RGB", size)
output.paste(canvas.convert("RGB"))
return output
This code defines a white-background delivery policy, not transparent output. Preserve a separate alpha-capable original if customers may later choose another background. The transparency guide explains why converting RGBA directly to RGB is not equivalent to intentional compositing.
How should you test layout behavior before shipping?
Use synthetic fixtures whose expected dimensions and edge content are known. These tests verify processing behavior independently of paid generation and make regressions reproducible.
Append this third block and run python3 resize_delivery.py. It checks padding, center cropping, orientation handling, and the no-upscaling rule without network access.
if __name__ == "__main__":
from tempfile import TemporaryDirectory
source = Image.new("RGBA", (400, 200), (255, 0, 0, 255))
fitted = derivative(source, (100, 100), "fit")
cropped = derivative(source, (100, 100), "crop")
assert fitted.size == cropped.size == (100, 100)
assert fitted.getpixel((50, 0)) == (255, 255, 255)
assert fitted.getpixel((50, 50)) == (255, 0, 0)
assert cropped.getpixel((50, 0)) == (255, 0, 0)
try:
derivative(source, (800, 800), "crop")
except ValueError:
pass
else:
raise AssertionError("upscaling was accepted")
with TemporaryDirectory() as folder:
path = Path(folder) / "oriented.jpg"
fixture = Image.new("RGB", (40, 20), "red")
exif = Image.Exif()
exif[274] = 6
fixture.save(path, exif=exif)
assert load_source(path).size == (20, 40)
result = Path(folder) / "tile.png"
fitted.save(result, format="PNG")
with Image.open(result) as reopened:
assert reopened.size == (100, 100)
assert reopened.mode == "RGB"
print("resize delivery tests passed")
Add approved real fixtures for labels, transparent edges, off-center subjects, and portrait compositions. Technical validity does not establish that a crop represents the product accurately. Keep composition review separate from pixel-dimension assertions.
How does local resizing change generation cost accounting?
Count model requests separately from locally produced derivative files. As of November 13, 2026, the supplied GenRelay prices imply that 100 generated pictures cost $1.40 with GPT-image-2 at $0.014 per picture, or $2.00 with Nano Banana 2 at its $0.020 1K rate.
Nano Banana Pro costs $3.00 for 100 images at either the $0.030 1K or 2K rate, and $4.20 at its $0.042 4K rate. Nano Banana 2's $0.036 4K rate gives $3.60 for 100 images. These figures exclude storage, processing, delivery, and any separately generated revisions.
Producing three thumbnails from each of those 100 originals creates 300 derivatives, not 300 additional model requests. Choose higher generation resolution when the application needs source detail, not because a CSS placement happens to require another file size. Keep an explicit policy for when insufficient source dimensions justify another paid attempt.
What do developers ask about image resizing?
Does resizing improve model output detail?
No. Increasing dimensions interpolates pixels. It does not establish that additional product detail is accurate or present in the source.
Should every thumbnail be square?
No. Define dimensions by placement. Fit with padding when preserving the complete subject matters more than filling the rectangle.
Can one original support multiple delivery formats?
Yes, subject to your color, transparency, and quality requirements. Derive each output from the approved original, not from another compressed derivative.
Should a resize failure automatically regenerate the image?
No. Diagnose decoding, policy, and layout failures first. A configuration error will usually persist across new paid generation attempts.