Responsive Images and Thumbnails
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. A backend that stores one big image per upload makes every client download too much. The fix is a small set of precomputed or on-demand variants, described here in terms of what the server produces. The HTML that consumes them is in native HTML images.
Variant strategy
- Width breakpoints
-
Choose a short list of widths that cover the slots in your layout, for example 320, 640, 960, 1280 and 1920. Each extra width multiplies storage and encode work. Pick widths from real slot sizes, not from device widths, and prefer roughly 1.5x steps over very fine ones, because the saving between two close widths is small.
- Density variants
-
A 2x display needs twice the pixels in the same CSS slot. Either list a larger width in
srcset(width descriptors, recommended) or emit1x/2xdescriptors for fixed-size images such as avatars. - Aspect-ratio crops
-
Thumbnails in a grid need identical aspect ratios, or the layout jumps. Decide the ratio in the product (for Bookshelf, covers are 2:3) and crop on the server, not with CSS only, so the bytes sent match the pixels shown.
- Fit modes
-
coverfills the box and crops the overflow.containfits the whole image and letterboxes.insidefits the image within the box, keeping its aspect ratio, and is the usual choice for article images. None of these modes prevents upscaling on its own. Never upscale: a small original gets a variant at its own size, not a blurry big one. In sharp, addwithoutEnlargement: true; withvips thumbnail, pass--size down. - Smart crop
-
Plain centre crop cuts faces off. Libraries offer attention-based crops (libvips
attentionandentropystrategies, exposed by sharp asposition: 'attention'), or you can send a focal point from the client, or call an image-analysis service. Store the focal point with the image so later variants stay consistent.
Naming and storage keys
Use deterministic keys that encode what the variant is, so no database lookup is needed to compute a URL:
covers/<id>/original.jpg private bucket, with EXIF, never public
covers/<id>/w320.avif
covers/<id>/w320.webp
covers/<id>/w320.jpg
covers/<id>/w640.avif
...
Include a content hash or version in the key when the image can change (w640-3f9a1c.avif), so each URL is
immutable and can be cached forever. Never overwrite a key that a CDN may have cached: change the key instead.
Eager versus on-the-fly generation
| Eager (at upload) | On-the-fly (at first request) | |
|---|---|---|
How |
A worker produces all variants after upload, see upload pipelines. |
An image service or edge function produces a variant when it is first requested and a CDN caches it. |
Pros |
Predictable latency, no compute on the read path, easy to audit. |
No wasted variants, new sizes need no backfill, one URL scheme for every size. |
Cons |
Storage for variants nobody requests, backfill job for new breakpoints. |
First request is slow, and an open resizing endpoint is an abuse and cost risk. Sign the URLs or whitelist sizes. |
Fits |
A fixed set of sizes, user-generated content. |
Large catalogues, editorial sites, changing layouts. |
Mixed strategies are common: eagerly produce a small and a large variant, and resize everything else on demand. Managed on-demand options are covered in the cloud pages: AWS, Google Cloud and Azure. Image CDNs such as Cloudinary and imgix accept transformations in the URL.
Worked example: how many widths
The cover grid of the running example uses sizes="(min-width: 60em) 20vw, 50vw", so a cover is half the viewport wide below 960 CSS pixels and a fifth of it above. The browser multiplies the slot
by the device pixel ratio and takes the smallest candidate that is at least that wide, see
native HTML images. That is enough to predict what each ladder costs. The AVIF sizes of the cover at the
candidate widths (Pillow, quality 60, speed 6) are 6,649 B at 320, 8,624 at 400, 10,023 at 480, 12,690 at 640, 16,125 at 800, 18,590 at 960, 23,856 at 1200 and 25,174 at 1280. Six representative visitors, and what
each of three ladders sends them (the last figure is how many times more pixels than needed were delivered):
| Visitor | Needed | Ladder A: 320, 640, 1280 | Ladder B: 320, 480, 640, 960, 1280 | Ladder C: 400, 800, 1200 |
|---|---|---|---|---|
Phone 360 px at 3x |
540 px |
640 px, 12,690 B, 1.4 x |
640 px, 12,690 B, 1.4 x |
800 px, 16,125 B, 2.2 x |
Phone 390 px at 3x |
585 px |
640 px, 12,690 B, 1.2 x |
640 px, 12,690 B, 1.2 x |
800 px, 16,125 B, 1.9 x |
Tablet 768 px at 2x |
768 px |
1280 px, 25,174 B, 2.8 x |
960 px, 18,590 B, 1.6 x |
800 px, 16,125 B, 1.1 x |
Laptop 1440 px at 2x |
576 px |
640 px, 12,690 B, 1.2 x |
640 px, 12,690 B, 1.2 x |
800 px, 16,125 B, 1.9 x |
Desktop 1920 px at 1x |
384 px |
640 px, 12,690 B, 2.8 x |
480 px, 10,023 B, 1.6 x |
400 px, 8,624 B, 1.1 x |
Desktop 2560 px at 1x |
512 px |
640 px, 12,690 B, 1.6 x |
640 px, 12,690 B, 1.6 x |
800 px, 16,125 B, 2.4 x |
Total bytes sent |
88,624 B |
79,373 B |
89,249 B |
|
AVIF bytes stored per cover |
44,513 B (3 files) |
73,126 B (5 files) |
48,605 B (3 files) |
Ladder B sends 10 percent fewer bytes than A to this audience and costs 64 percent more storage (and 67 percent more encodes) per cover, and ladder C, with the same number of files as A, is no better, because the widths are not matched to the slots that users actually have. The lesson is the one stated above: choose widths from the slot sizes of the layout times the pixel ratios that visit it, then count what an extra rung buys. Where the layout is dominated by one slot size, one extra rung next to it (here 480 and 960) is worth more than evenly spaced widths. Across all three formats, the nine files of ladder A total 311,961 bytes per cover against an original of 658,544, so a million covers occupy about 312 GB of variants, and the two extra rungs of ladder B (480 and 960) raise the AVIF share of that by about 64 percent: put that number against the 10 percent of bandwidth before adding them.
Fit and crop, measured
The product decides the aspect ratio, and the server enforces it. For the 2400 by 3600 cover, a square 640 by 640 thumbnail (as in a search result) can be taken three ways with libvips (through pyvips
Image.thumbnail(..., height=640, crop=...)): the centre, the most visually "attention-grabbing" window, or the window with the highest entropy. All three returned 640 by 640, but they cut different parts. In sharp 0.35.5 (libvips 8.18.7), after
the cover is scaled to 640 by 960, the crop removed 160 pixels from the top and 160 from the bottom with position: 'centre', 130 from the top with 'attention' (30 pixels higher), and 280 from the top with 'entropy' (120 pixels lower: it keeps more of the
lower part of the cover). withoutEnlargement: true on a 400 by 600 original asked for width 1280 returned 400 by 600. The window depends on the content, so:
-
Compute the crop once at upload and store the focal point with the image record, as stated in the variant strategy, so the thumbnail does not jump when the library is upgraded.
-
Use
coverwith a fixed ratio for grids andinsidefor article images, and never let CSSobject-fitdo the crop on a full-size image. -
Keep the original, uncropped master. A new layout with a different ratio then needs a backfill, not a re-upload.
A signed, negotiated origin
On-the-fly generation needs two protections: an allow list of widths, and signed URLs, otherwise anyone can make the origin generate a thousand variants per image. The origin below is a few
lines of Python standard library. It serves a stored variant (generation is the same code with a cache in front), chooses AVIF, WebP or JPEG from the Accept header, answers conditional requests, and
refuses unsigned or off-list requests:
import hashlib, hmac, os, re
from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlparse
SECRET = b"change-me"
TYPES = {"avif": "image/avif", "webp": "image/webp", "jpg": "image/jpeg"}
WIDTHS = {320, 640, 1280} # the allow list
def sign(path: str, width: int) -> str:
return hmac.new(SECRET, f"{path}?w={width}".encode(), hashlib.sha256).hexdigest()[:16]
def negotiate(accept: str) -> str:
accept = accept or ""
if "image/avif" in accept: return "avif"
if "image/webp" in accept: return "webp"
return "jpg"
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url = urlparse(self.path)
m = re.fullmatch(r"/img/(?P<id>[0-9a-f]{4})", url.path) # /img/b81f?w=640&sig=...
q = parse_qs(url.query)
if not m or "w" not in q or not q["w"][0].isdigit():
return self.send_error(400)
width = int(q["w"][0])
if width not in WIDTHS:
return self.send_error(400, "width not allowed")
if not hmac.compare_digest(q.get("sig", [""])[0], sign(url.path, width)):
return self.send_error(403, "bad signature")
fmt = negotiate(self.headers.get("Accept"))
body = open(os.path.join("covers", m["id"], f"w{width}.{fmt}"), "rb").read()
etag = '"' + hashlib.sha256(body).hexdigest()[:16] + '"'
if self.headers.get("If-None-Match") == etag:
self.send_response(304); self.send_header("ETag", etag); self.send_header("Vary", "Accept"); self.end_headers(); return
self.send_response(200)
self.send_header("Content-Type", TYPES[fmt])
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "public, max-age=31536000, immutable")
self.send_header("ETag", etag)
self.send_header("Vary", "Accept")
self.end_headers(); self.wfile.write(body)
Requests against it with curl (the signature for w=640 was computed with sign("/img/b81f", 640)):
$ curl -sD - -o /dev/null -H 'Accept: image/avif,image/webp,*/*' "http://127.0.0.1:18431/img/b81f?w=640&sig=90c69a3c2a96a694"
HTTP/1.0 200 OK
Content-Type: image/avif
Content-Length: 12664
Cache-Control: public, max-age=31536000, immutable
ETag: "3b32e56b3d478e82"
Vary: Accept
(Accept: image/webp,*/*) -> 200 image/webp, Content-Length 24354
(Accept: text/html) -> 200 image/jpeg, Content-Length 47365
(If-None-Match: "3b32e56b3d478e82") -> 304 Not Modified, with ETag and Vary
(w=641, valid signature for 640) -> 400 width not allowed
(w=320 with the signature for 640) -> 403 bad signature
(no signature) -> 403 bad signature
The three bodies for one URL are the point of Vary: Accept: the CDN must key its cache on the format, and since browsers send many different Accept strings, normalise the header at the CDN to the
three values this code produces (or key on a computed format) so the cache does not fragment. Signing the width into the URL means a tampered w fails (403), and the allow list bounds the work even for signed URLs.
Prefer the <picture> approach shown below when the CDN cannot normalise Accept.
Cache headers and CDN invalidation
-
Immutable, content-addressed variants:
Cache-Control: public, max-age=31536000, immutable. -
Variants at a stable URL that can change: a short
max-ageplusstale-while-revalidate, and an ETag. -
If the server negotiates the format by
Accept, addVary: Acceptor the CDN may serve the wrong format. -
Prefer new keys to invalidation. Invalidation by path is slow, billed by some CDNs and still leaves browser caches untouched.
References: MDN HTTP caching and MDN Cache-Control.
What the backend must emit for srcset, sizes and picture
The browser chooses the file, but it can only choose among what the API describes. Return the list of variants with the image metadata, so the frontend can build the markup without guessing URLs:
{
"id": "b81f",
"width": 2400,
"height": 3600,
"blurhash": "TKAeBpR,9GiXf8WC0Lt6?GN1j[t6",
"variants": [
{ "format": "avif", "width": 320, "url": "https://cdn.example.com/covers/b81f/w320.avif" },
{ "format": "webp", "width": 320, "url": "https://cdn.example.com/covers/b81f/w320.webp" },
{ "format": "jpeg", "width": 320, "url": "https://cdn.example.com/covers/b81f/w320.jpg" },
{ "format": "avif", "width": 640, "url": "https://cdn.example.com/covers/b81f/w640.avif" },
{ "format": "webp", "width": 640, "url": "https://cdn.example.com/covers/b81f/w640.webp" },
{ "format": "jpeg", "width": 640, "url": "https://cdn.example.com/covers/b81f/w640.jpg" },
{ "format": "avif", "width": 1280, "url": "https://cdn.example.com/covers/b81f/w1280.avif" },
{ "format": "webp", "width": 1280, "url": "https://cdn.example.com/covers/b81f/w1280.webp" },
{ "format": "jpeg", "width": 1280, "url": "https://cdn.example.com/covers/b81f/w1280.jpg" }
]
}
The blurhash is the real string of the running example, produced from the 64 by 96 reduction of the cover with 3 by 4 components, see
the Python page and the Java page for the code that wrote it.
Always include the intrinsic width and height of the original (or of the aspect ratio) so the page can reserve
space and avoid layout shift, and the BlurHash for the placeholder, see
BlurHash. The client then builds:
<picture>
<source type="image/avif" srcset="…/w320.avif 320w, …/w640.avif 640w" sizes="(min-width: 60em) 20vw, 50vw">
<source type="image/webp" srcset="…/w320.webp 320w, …/w640.webp 640w" sizes="(min-width: 60em) 20vw, 50vw">
<img src="…/w640.jpg" width="2400" height="3600" alt="Cover of Moby-Dick" decoding="async">
</picture>
sizes describes the slot width, not the image width, and only the page author knows it. References:
MDN responsive images and
MDN picture element.
Related pages
-
Next.js Image, which can call a loader like the signed origin above