Agent Wranglers

MED-7Recommended

Make image sizes from a fixed list

Resize images only to widths and formats on a fixed list in your code. An image address that asks for any other size answers 400 and never reaches the resizer.

How to do it

An image service that resizes on demand from parameters in the address, such as ?w=1234, lets anyone make it render thousands of sizes. Each one costs processing time and a cached copy. Make the common sizes when the upload is confirmed, and make rare ones on the first request, cached for good. Either way, choose from one list, such as 320, 640, 1024 and 2048 pixels wide. When you need free parameters, sign them with an HMAC so only your own pages can ask. The image is first rebuilt without metadata, as Rebuild every uploaded image says. The widths feed srcset, as Send small, modern images describes.

Examples

JavaScript example

const IMAGE_WIDTHS = new Set([320, 640, 1024, 2048]);
const IMAGE_FORMATS = new Set(['avif', 'webp', 'jpeg']);

export function parseImageRequest(params) {
  const width = Number(params.get('w'));
  const format = params.get('f') ?? 'jpeg';
  if (!IMAGE_WIDTHS.has(width) || !IMAGE_FORMATS.has(format)) return null;
  return { width, format };
}

Python example

IMAGE_WIDTHS = frozenset({320, 640, 1024, 2048})
IMAGE_FORMATS = frozenset({"avif", "webp", "jpeg"})

def parse_image_request(params: dict[str, str]) -> tuple[int, str] | None:
    width = int(params.get("w", "0")) if params.get("w", "").isdigit() else 0
    image_format = params.get("f", "jpeg")
    if width not in IMAGE_WIDTHS or image_format not in IMAGE_FORMATS:
        return None
    return width, image_format

How to check

Request an image at each width on the list, and each answers 200. Request it at 1,234 pixels wide, and the answer is 400 with no new object in storage.

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/files-and-media/images/fixed-image-sizes">Agent Wranglers files and media playbook</a>. In code you write, add a comment next to it with the same link.