Sub topic 10
Generating image variants and modern formats
This chapter covers the worker that turns one uploaded image into several sizes and formats. It assumes you have read the chapters on presigned uploads and the event-driven pipeline. You should know that a completed upload triggers a job, that originals live in object storage, and that the job runs outside the request path. You should also be comfortable reading Python.
Why store variants at all
A phone photo is often 4000 pixels wide and several megabytes. A profile page that shows it in a 200-pixel slot wastes bandwidth, slows rendering, and raises egress cost. The fix is to keep the original and derive smaller files from it.
Variants are also a security and consistency tool. Re-encoding an image produces a new file written by your own code, so unusual container tricks, embedded metadata, and malformed trailing data in the original are not carried into what you serve. This does not replace validation or scanning. It adds one more layer.
A typical variant set looks like this:
| Variant | Width | Use |
|---|---|---|
| thumb | 320 px | lists, grids, avatars |
| medium | 800 px | article bodies, cards |
| large | 1600 px | full-width hero images, high-density screens |
| original | as uploaded | private archive, future re-processing |
Choose widths from your real layouts, not from habit. Every extra width multiplies storage and CDN cache entries.
Where the worker sits
The worker is one consumer of the "upload completed" event. It reads the original from the private bucket and writes variants under content-addressed keys. The CDN later serves those keys.
The queue matters. Object-storage events are delivered at least once, so the same event can arrive twice. The worker must be idempotent: running it twice on the same input must leave the same result. Deriving keys from a hash of the original gives you that for free.
A variant worker
This function downloads an original, normalizes it, produces WebP files at several widths, and uploads them with long-lived cache headers. It needs boto3 and Pillow.
import hashlib
import io
import boto3
from PIL import Image, ImageOps
s3 = boto3.client("s3")
WIDTHS = [320, 800, 1600]
Image.MAX_IMAGE_PIXELS = 50_000_000 # reject decompression bombs
CACHE_CONTROL = "public, max-age=31536000, immutable"
def make_variants(src_bucket, src_key, dest_bucket):
body = s3.get_object(Bucket=src_bucket, Key=src_key)["Body"].read()
digest = hashlib.sha256(body).hexdigest()[:12]
with Image.open(io.BytesIO(body)) as img:
img = ImageOps.exif_transpose(img) # apply camera rotation
mode = "RGBA" if "A" in img.getbands() else "RGB"
img = img.convert(mode)
# Never upscale: cap each target at the original width.
widths = sorted({min(w, img.width) for w in WIDTHS})
keys = []
for w in widths:
h = round(img.height * w / img.width)
resized = img.resize((w, h), Image.LANCZOS)
buf = io.BytesIO()
resized.save(buf, "WEBP", quality=80, method=4)
key = f"media/{digest}/w{w}.webp"
s3.put_object(
Bucket=dest_bucket,
Key=key,
Body=buf.getvalue(),
ContentType="image/webp",
CacheControl=CACHE_CONTROL,
)
keys.append(key)
return keysSeveral details in this code are deliberate:
exif_transposebakes the camera's rotation flag into the pixels. Without it, a portrait photo can appear sideways after you strip metadata.- Saving through Pillow without passing
exif=drops EXIF data, including GPS coordinates. This protects users who did not know their photo carried a location. MAX_IMAGE_PIXELSmakes Pillow warn above the limit and raiseDecompressionBombErrorabove twice the limit. A small file can decode to billions of pixels, so set a limit and treat that exception as a rejected upload.- The key contains the hash of the original, so a retry overwrites identical bytes at identical keys. A re-upload of the same file reuses existing variants.
Choosing formats
JPEG remains the universal fallback. Newer formats compress better at similar visual quality.
| Format | Strengths | Costs |
|---|---|---|
| JPEG | Works everywhere, fast to encode | Larger files, no transparency |
| PNG | Lossless, transparency | Very large for photos |
| WebP | Smaller than JPEG, supports transparency and animation, supported by current major browsers | Slightly slower encode |
| AVIF | Often smaller than WebP at similar quality | Much slower encode, library support varies |
For a first version, produce WebP only. It gives a clear size win with little operational risk. Add AVIF when your measurements show it is worth the encode time. Check that your Pillow build can write it (".avif" in Image.registered_extensions()) before relying on it, because support depends on the version and installed plugins.
Keep JPEG or PNG fallbacks only if you must support old clients. Many products now serve WebP to everyone and skip the fallback.
Telling the browser which file to fetch
You have two ways to offer multiple formats and sizes.
- Markup-driven. The page lists the variants itself, using
srcsetandsizesfor widths and apictureelement with severalsourceentries for formats. The browser picks one. The CDN needs no special logic, and every URL caches independently. The cost is that your templates must know the variant URLs. - Header-driven. One URL returns different formats depending on the request's
Acceptheader. Templates stay simple, but the response must carryVary: Accept, or a cache may hand an AVIF file to a browser that cannot decode it.Varyalso splits the cache into more entries and can lower the hit rate.
Prefer markup-driven selection for a first design. It is easier to debug because the URL fully identifies the bytes, which matches the immutable-URL approach in the CDN chapter.
Eager versus on-demand generation
You can create variants when the upload completes (eager) or the first time someone requests them (on-demand).
| Approach | Advantages | Drawbacks |
|---|---|---|
| Eager | Predictable latency, simple CDN setup, failures surface early | Pays for variants nobody views, adding a size means a backfill |
| On-demand | Pays only for what is viewed, new sizes need no backfill | First request is slow, needs a resizing service, open to abuse |
On-demand systems must restrict parameters. If any client can request w=1, w=2, w=3, and so on, each unique URL is a cache miss and a CPU-bound resize. Accept widths only from an allowlist, and sign the URLs if the set of images is private.
Edge cases to handle
- Animated images.
img.convertandresizekeep only the first frame in this worker. Detect animation (getattr(img, "is_animated", False)) and either reject it, keep the first frame deliberately, or send it to a video pipeline. - Color profiles. CMYK and wide-gamut images look wrong if you drop the profile without converting. Convert to sRGB before saving for the web.
- HEIC from iPhones. Pillow cannot read HEIC without a plugin. Decide whether to support it or have the client convert before upload.
- SVG. It is XML that can contain scripts, not a raster image. Do not pass it through the same worker. Reject it from avatar uploads, or sanitize it and serve it as a download, as the serving-security chapter explains.
- Partial failure. If the worker writes two of three variants and crashes, the retry rewrites all three to the same keys. Record the image as ready in your database only after every variant exists.
- Poison files. A file that always fails should go to a dead-letter queue after a few attempts, and the user-facing record should show a failed state instead of hanging.
Exercises
Exercise
A worker produces variants at keys like media/<hash of original>/w800.webp and uploads them with "Cache-Control: public, max-age=31536000, immutable". A developer changes the WebP quality setting from 80 to 70 and redeploys, expecting existing images to update. Why will users keep seeing the old files, and what are two ways to fix it?
Show answer
The key depends only on the original's hash, so the URLs stay the same, and the CDN and browsers may legally reuse the cached bytes for a year. Fix it by including the encoding settings in the key (for example a version segment such as media/v2/<hash>/w800.webp or a hash of the original plus the settings), so changed output gets a new URL. Alternatively, rerun the job to overwrite the objects and invalidate the CDN paths, though that is slower and less reliable than changing the URL.
Exercise
Your worker receives the same upload-completed event twice at nearly the same time. Explain why the worker in this chapter still behaves correctly, and name one thing that could go wrong if keys were random UUIDs instead.
Show answer
Both runs read the same original and compute the same hash, so they write identical bytes to identical keys. The second write simply overwrites the first with the same content. With random UUID keys, each run would create its own set of variants, leaving duplicate orphaned objects that the database might not reference, which wastes storage and complicates cleanup.