AI Image API Contact Sheet: Build Review Previews with Python
Your application generates twenty product images, but a reviewer must open twenty individual downloads to compare composition and spot missing details. An AI image API contact sheet puts labeled thumbnails on one canvas so reviewers can triage a batch before opening individual originals. The useful implementation preserves the relationship between every thumbnail and its output record, rather than treating the preview as another generated asset.
This tutorial builds that review step after your backend downloads completed outputs from the GenRelay image API. It uses Python 3 and Pillow to process local, application-owned files. The code does not submit generation requests or depend on undocumented model response fields. A contact sheet is a grid of small image previews with labels; it supports human selection without replacing full-resolution inspection.
What should an image review manifest contain?
A review manifest should map a stable application output identifier to a local source path and display label. A manifest is a structured list describing the inputs to a processing job. Create it from successful download records, rather than discovering arbitrary files in a shared directory.
Use identifiers such as asset-001, not expiring URLs or access tokens. The preview label should remain meaningful after files move between storage systems. Keep tenant ownership, original storage keys, model names, prompt versions, and approval history in your database. The contact sheet needs only the minimum fields that help a reviewer locate an original.
For example, save this JSON as manifest.json beside two downloaded image files:
[
{"id": "asset-001", "path": "first.png"},
{"id": "asset-002", "path": "second.png"}
]
This is your application's input format, not a GenRelay response schema. Relative paths in the following implementation resolve against the manifest directory. The loader rejects paths outside that directory, including symbolic links that resolve elsewhere. Run each review job in its own private directory so path containment also matches your ownership boundary.
How do you load images without losing labels or orientation?
Load each permitted still image, normalize its display orientation, and fit it inside a fixed thumbnail box. Exchangeable Image File Format, or EXIF, can contain orientation instructions that change how an image should be displayed. Applying those instructions before resizing prevents a portrait thumbnail from appearing sideways.
Install Pillow with python3 -m pip install Pillow. Save the following as contact_sheet.py. Its limits are an example application policy, not published provider quotas. The code accepts JPEG, PNG, and WebP still images, rejects multi-frame sources, and sets a decompression threshold before loading pixels.
import json
import re
import warnings
from pathlib import Path
from PIL import Image, ImageDraw, ImageOps
Image.MAX_IMAGE_PIXELS = 16_000_000
ALLOWED = {"JPEG", "PNG", "WEBP"}
CELL_W, CELL_H = 280, 240
def load_items(manifest):
manifest = Path(manifest).resolve()
if manifest.stat().st_size > 64_000:
raise ValueError("Manifest too large")
records = json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(records, list) or not 1 <= len(records) <= 24:
raise ValueError("Expected 1 to 24 records")
root, seen, items = manifest.parent, set(), []
for record in records:
label = record["id"]
if not isinstance(label, str) or not re.fullmatch(
r"[A-Za-z0-9_-]{1,24}", label
) or label in seen:
raise ValueError("Invalid or repeated identifier")
seen.add(label)
path = (root / record["path"]).resolve()
if not path.is_relative_to(root):
raise ValueError("Source outside job directory")
if path.stat().st_size > 20_000_000:
raise ValueError("Source exceeds byte limit")
with warnings.catch_warnings():
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(path) as source:
if source.format not in ALLOWED:
raise ValueError("Unsupported image format")
if getattr(source, "n_frames", 1) != 1:
raise ValueError("Expected a still image")
if source.width * source.height > 16_000_000:
raise ValueError("Source exceeds pixel limit")
source.load()
thumb = ImageOps.exif_transpose(source).convert("RGBA")
thumb.thumbnail((CELL_W - 24, CELL_H - 48))
items.append((label, thumb))
return items
The path checks assume another process cannot replace files during the job. Enforce that assumption with private job directories and restricted writers. Byte limits and Pillow warnings reduce accidental resource spikes, but they do not replace worker memory limits or decoder updates.
The conversion to RGBA retains transparency for composition. RGBA means red, green, blue, and alpha; alpha describes pixel opacity. This example places transparent areas over a light gray review background. It does not infer the background your final product page should use.
How do you render a stable contact sheet with Python?
Render records in manifest order and center each thumbnail inside a cell with its output identifier underneath. Stable order matters because reviewers often refer to the same position while discussing a batch. Store the manifest version with the preview so a later regeneration cannot silently change what “third image” means.
Append this code to contact_sheet.py:
def render(items, destination):
if not 1 <= len(items) <= 24:
raise ValueError("Expected 1 to 24 items")
columns = min(4, len(items))
rows = (len(items) + columns - 1) // columns
canvas = Image.new(
"RGBA", (columns * CELL_W, rows * CELL_H),
(238, 238, 238, 255),
)
draw = ImageDraw.Draw(canvas)
for index, (label, thumb) in enumerate(items):
left = (index % columns) * CELL_W
top = (index // columns) * CELL_H
x = left + (CELL_W - thumb.width) // 2
y = top + 12 + (CELL_H - 48 - thumb.height) // 2
canvas.alpha_composite(thumb, (x, y))
draw.text((left + 12, top + CELL_H - 26), label,
fill=(20, 20, 20, 255))
# Save newly composed pixels without copying source metadata.
with Path(destination).open("xb") as output:
canvas.convert("RGB").save(output, format="PNG")
return canvas.size
if __name__ == "__main__":
import sys
print(render(load_items(sys.argv[1]), sys.argv[2]))
Run python3 contact_sheet.py manifest.json review.png with a fresh destination. Exclusive file creation prevents accidental overwrites. Write to private staging storage, validate the completed file, and publish its storage reference only after success. A process crash can leave an incomplete staging file; remove that file during job cleanup.
The maximum preview measures 1120 by 1440 pixels for twenty-four records. These dimensions follow directly from four columns, six rows, and the configured cell size. They are not supported model output resolutions. The code fits images without cropping, so a wide banner may occupy less cell height than a portrait.
What can a contact sheet tell a reviewer?
A contact sheet helps compare framing, gross color differences, empty outputs, and repeated compositions across a batch. It cannot establish that small label text, product geometry, or fine surface details are correct. Thumbnail resizing can hide defects and change the apparent sharpness of an image.
Open selected originals at full resolution before approving them. If exact text matters, inspect it separately against the intended copy. If a product color is legally or commercially significant, use your established color review process; this example does not implement profile-aware color conversion. Treat previews as navigation aids rather than color proofs.
Follow the file format detection guide when validating downloaded bytes, and use output validation before marking assets ready. A review decision should point to an immutable output version so replacing a file cannot transfer approval to different content.
How much does generating the source batch cost?
Source generation cost depends on the selected model and resolution; composing an existing contact sheet does not require another generation request. The following USD arithmetic uses the supplied GenRelay rates as of November 30, 2026, assuming twenty successful single-image outputs and excluding retries, storage, and worker compute.
| Model and resolution | Price per image | Twenty images |
|---|---|---|
| Nano Banana Pro 1K or 2K | $0.030 | $0.60 |
| Nano Banana Pro 4K | $0.042 | $0.84 |
| Nano Banana 2 1K | $0.020 | $0.40 |
| Nano Banana 2 4K | $0.036 | $0.72 |
| GPT-image-2, quoted per picture | $0.014 | $0.28 |
These figures compare quoted billing units, not equivalent visual quality or identical resolution support. A rejected thumbnail should trigger review of its source record. Rebuilding a preview from stored originals avoids repeating paid generation merely to change labels or grid layout.
What should you test before adding batch review to your app?
Test record identity, visual placement, and rejection paths with synthetic local images before processing customer batches. Include portrait and landscape sources, a transparent PNG, an EXIF-rotated JPEG, duplicate identifiers, a multi-frame file, and a path escaping the job directory.
Assert the grid dimensions and verify representative pixels from each source land in the expected cell. Confirm rerunning against an existing destination fails. Keep your manifest and preview private to the same tenant, and authorize every request for an original independently of access to the contact sheet. A preview is still customer content even when its pixels are smaller.
What questions do developers ask about contact sheets?
Does making a contact sheet call the image generation API again?
No. This implementation reads previously downloaded local files and creates a derived PNG using Pillow. Generation is a separate operation with its own billing and lifecycle.
Can the preview preserve transparent backgrounds?
The example composites transparency onto gray and exports RGB. Keep the original alpha channel separately, and change the preview background deliberately if reviewers need to evaluate edge behavior.
Should one invalid image be silently skipped?
This loader fails the batch so record positions cannot shift unnoticed. A production interface can show an explicit failed cell, provided that the cell retains its original identifier and failure reason.
Is a contact sheet suitable for final product approval?
Use it for initial selection and comparison. Approve the immutable full-resolution output after checking the details relevant to your application, then store that decision against its exact asset version.