Sub topic 12
Generating the image widths you need
This chapter covers how to produce the files that srcset points to. It assumes you can write srcset with w descriptors and a sizes attribute, and that you know the difference between CSS pixels and device pixels. You also need a terminal with ImageMagick 7 or Node.js 18 or later for the examples.
The browser can only choose among files you have already made. If the set is poorly chosen, even a perfect srcset and sizes pair sends too many bytes or produces blurry images. This chapter shows how to pick widths, how to create them, and how to avoid common mistakes.
Start from the largest size you need
Every variant is a downscaled copy of one master image. Resizing down loses detail you can't get back, and resizing up only adds blur. So the master must be at least as wide as your largest variant.
To find the largest variant, take the widest CSS size the image can ever have and multiply it by the highest pixel density you want to serve.
- A content image that never exceeds 800 CSS pixels needs a 1600-pixel file to look sharp on a 2x screen.
- A full-width hero image on a layout capped at 1200 CSS pixels needs 2400 pixels for 2x screens. On a layout with no cap, it needs the widest viewport you intend to support, times the density.
Most teams stop at 2x. A 3x phone screen shows only small gains from the extra pixels. The file is much larger, because pixel count grows with the square of the scale.
Choose a set of widths
You do not need a file for every possible width. You need enough files that the browser never has to pick one much larger than necessary. Two approaches work well.
- Cover the layout breakpoints. List the CSS widths your image takes at each breakpoint (from your
sizesattribute), then add the 2x version of each. A layout with 400, 800, and 1200 CSS-pixel widths gives candidates of 400, 800, 1200, 1600, and 2400 pixels. - Use a geometric series. Start from a small width and multiply by roughly 1.5 to 2 for each step. For example, 400, 800, 1600 is a doubling series, and 400, 600, 900, 1350 is a 1.5 series. This suits layouts where the display width varies continuously.
More candidates mean a closer fit, but also more files to build, store, and cache. Adding a candidate stops paying off when the next size is less than about 20 to 25 percent larger than its neighbor. The savings are then too small to matter. Four to six widths per image is a common range.
| Situation | Suggested widths |
|---|---|
| Thumbnail shown at 200 CSS px, fixed | 200, 400 |
| Content image up to 800 CSS px | 400, 800, 1200, 1600 |
| Full-width hero up to 1600 CSS px | 640, 960, 1280, 1920, 2560 |
| Card grid, 25 to 50 percent of viewport | 300, 450, 600, 900, 1200 |
These are starting points. Check them against your own sizes values.
The generation pipeline
The pipeline has the same shape however you implement it.
Generating widths with ImageMagick
The simplest form is a shell loop that creates one file per width. The > flag after the geometry tells ImageMagick to shrink only when the source is larger than the target. Without it, a 1000-pixel source resized to 1600 would be enlarged and blurry.
for w in 400 800 1200 1600; do
magick photo.jpg -resize "${w}x>" -quality 80 "photo-${w}.jpg"
doneThe quotes around "${w}x>" stop the shell from treating > as output redirection.
Note that when the source is narrower than a target, this loop makes a file with the source's width but a name that claims otherwise. For example, photo-1600.jpg might really be 1000 pixels wide. If you then write 1600w for that file, the browser believes a false width. The script in the next section avoids this by reading the real width of each output.
For other formats, change the output extension. ImageMagick must have been built with WebP and AVIF support, so check with magick -list format.
for w in 400 800 1200 1600; do
magick photo.jpg -resize "${w}x>" -quality 75 "photo-${w}.webp"
magick photo.jpg -resize "${w}x>" -quality 50 "photo-${w}.avif"
doneQuality values are not comparable across formats. A quality of 50 in AVIF is not "worse" than 80 in JPEG. Compare the results by eye and by file size, and tune each format separately.
Generating widths and the srcset string with Node.js
A script can also build the srcset text, so it never drifts from the files on disk. This version uses the sharp library (npm install sharp). It skips widths larger than the source, applies EXIF rotation, and reports each file's real width.
// make-variants.mjs
import sharp from 'sharp';
import { mkdir } from 'node:fs/promises';
import path from 'node:path';
const input = process.argv[2];
if (!input) {
console.error('Usage: node make-variants.mjs <image>');
process.exit(1);
}
const widths = [400, 800, 1200, 1600];
const formats = [
{ name: 'avif', ext: 'avif', quality: 50 },
{ name: 'webp', ext: 'webp', quality: 75 },
{ name: 'jpeg', ext: 'jpg', quality: 80 },
];
const outDir = 'out';
await mkdir(outDir, { recursive: true });
const base = path.parse(input).name;
const meta = await sharp(input).metadata();
// EXIF orientations 5 to 8 swap width and height once rotated.
const sourceWidth = meta.orientation >= 5 ? meta.height : meta.width;
const usable = widths.filter((w) => w <= sourceWidth);
for (const format of formats) {
const entries = [];
for (const w of usable) {
const file = path.join(outDir, `${base}-${w}.${format.ext}`);
const info = await sharp(input)
.rotate()
.resize({ width: w, withoutEnlargement: true })
.toFormat(format.name, { quality: format.quality })
.toFile(file);
entries.push(`${file} ${info.width}w`);
}
console.log(`${format.name}:\n srcset="${entries.join(', ')}"`);
}Run it with node make-variants.mjs photo.jpg. The output gives one srcset value per format, ready to paste into source and img elements.
Naming and file organization
Put the width in the file name, as in photo-800.jpg. This makes the srcset easy to read and check by hand. A few habits keep a large set manageable:
- Use one naming pattern for every image:
name-WIDTH.ext. - Keep the master out of the public output folder, so no one links to a 6000-pixel original by accident.
- Serve variants with long cache lifetimes. If the content changes, change the file name (for example, with a content hash), because the same URL is expected to return the same image.
Pitfalls
Writing the wrong width. The number in a w descriptor must be the file's real intrinsic width in pixels. If it is wrong, the browser makes its choice from false data, and the page still loads without any error. Read widths from the generated files, as the script above does.
Skipping the intrinsic ratio. All variants of one image must share the same aspect ratio, because the width and height attributes on the img describe a single ratio. Resizing by width only ("${w}x") preserves the ratio. Cropping each size differently is art direction, and it belongs in picture with media.
Generating too many files. Ten widths in three formats is thirty files per image. Build time, storage, and CDN cache entries grow with it. Fewer, well-spaced widths usually perform nearly as well.
Compressing too hard or too little. A high-resolution file at heavy compression can be smaller than a low-resolution file at light compression, and often looks better. Test quality settings on real photos rather than relying on defaults.
Re-encoding from a variant. Always generate each variant from the master. Resizing a 400-pixel JPEG to make a 200-pixel file stacks compression loss on compression loss.
Upscaling. A 1600-pixel file made from a 1000-pixel source adds bytes without adding detail. Use > in ImageMagick, withoutEnlargement in sharp, or filter the width list.
Automating beyond a script
Once you have more than a handful of images, a script run by hand becomes tedious. Build tools, static site generators, and image CDNs can create variants for you. Some take the width list as configuration and produce the srcset automatically. An image CDN generates widths on request from a URL parameter, so you skip the build step and only write the srcset URLs.
Whichever you choose, the same decisions apply. Pick the widest size from the layout and density. Choose a modest set of widths. Keep each file's declared width equal to its real width. These are the points to check in any tool's output.
Exercise
Your layout shows an image at up to 600 CSS pixels wide, and you want sharp results on 2x screens. The master image is 1000 pixels wide. What is the largest variant you can honestly offer, and what should you do about the 2x case?
Show answer
The largest honest variant is 1000 pixels, because a larger file would be an upscaled copy with no extra detail. A 2x screen needs 1200 pixels for a 600 CSS-pixel image, so the 1000-pixel file will look slightly soft there. The fix is to get a larger master (at least 1200 pixels). Until then, list only widths up to 1000 in the srcset, using the file's real width in its descriptor.
Exercise
A script produces photo-1600.jpg from a 1000-pixel-wide master without enlargement protection, and the srcset says "photo-1600.jpg 1600w". Describe the problem and give two ways to prevent it.
Show answer
The file may be 1000 pixels wide (or an upscaled, blurry 1600) while the srcset claims 1600w, so the browser's selection rests on a false width. Prevention: filter the width list to values no larger than the source width, and read each output's real width (for example from sharp's toFile result) when building the srcset. Using the ImageMagick ">" flag or sharp's withoutEnlargement stops upscaling, but you must still read the real width for the descriptor.