Dynamic Images in Web Development: Examples and Use Cases
Learn responsive images, on-demand resizing, format negotiation, caching, accessibility, and production patterns for dynamic image delivery.
Dynamic images are images selected or transformed at request time. The browser can choose an appropriate source with srcset, sizes and picture; a server, image API or CDN can resize, crop, compress or convert an image based on URL parameters, client hints or application context. The goal is to deliver the right dimensions, resolution and format for each device instead of sending one oversized file everywhere. Google Cloud describes this as delivering high-quality images in optimal format, dimensions and resolution for the accessing device.
What dynamic images mean
A static image URL always points to one authored file. A dynamic image URL or HTML source can produce different bytes for different requests:
- Browser selection: the browser chooses among files listed in
srcsetorpicture. - Server transformation: an application resizes, crops, compresses or converts the original when requested.
- Image CDN: an edge service generates variants from URL parameters and caches them close to visitors.
- Application composition: a pipeline normalizes uploads, applies a focal-point crop, creates thumbnails or renders user-specific graphics.
Image CDNs can reduce transferred bytes and origin work, but every distinct transformation combination may create a separate cache entry. In a measured 2023 study, images represented 41% of transmitted web data; web.dev reports that image CDN workflows can save 40–80% of image bytes in suitable cases (study, web.dev).
Use responsive HTML when the browser should choose
Use width descriptors when the same image composition is valid at different rendered sizes. sizes tells the browser how wide the slot will be; it can then select the nearest useful candidate.
<img
src="/images/hero-1280.jpg"
srcset="
/images/hero-480.jpg 480w,
/images/hero-768.jpg 768w,
/images/hero-1280.jpg 1280w,
/images/hero-1920.jpg 1920w"
sizes="(max-width: 700px) 100vw, (max-width: 1200px) 70vw, 840px"
width="840"
height="560"
alt="A mountain trail at sunrise"
decoding="async"
/>
Use pixel-density descriptors when the rendered CSS size is fixed:
<img
src="/avatar-1x.jpg"
srcset="/avatar-1x.jpg 1x, /avatar-2x.jpg 2x"
width="96"
height="96"
alt="Profile photo"
/>
Use picture for art direction or format-specific sources. The browser evaluates sources in order and falls back to the nested img.
<picture>
<source media="(max-width: 600px)" srcset="/hero-mobile.jpg" />
<source type="image/avif" srcset="/hero.avif" />
<source type="image/webp" srcset="/hero.webp" />
<img src="/hero.jpg" width="1600" height="900" alt="Product dashboard" />
</picture>
These techniques are covered in MDN’s responsive images guide. They avoid downloading a desktop asset to every mobile user, while keeping selection under browser control.
Generate variants from URL parameters
A transformation service can encode width, crop, quality and format in a URL. One service may use a path such as /images/hero.jpg?width=800&quality=75&format=webp; another may use a documented operation string. Google Cloud’s imop syntax chains operations such as Resize, Compress and Convert.
<img
src="https://img.example.test/hero.jpg?width=800&quality=75&format=webp"
width="800"
height="450"
alt="Mountain trail"
/>
Order changes the output. Cropping to a focal rectangle and then resizing differs from resizing first and cropping afterward. Put operations in the order that matches the desired visual result, and document that order in your image pipeline. See Google Cloud’s configuration reference and its use cases and ordering notes.
Use an image CDN for on-demand delivery
An image CDN generates a variant on the first request, stores it at the edge and serves cache hits subsequently. Cloudflare documents URL and Worker interfaces for real-time resize, crop and effects, plus two responsive approaches: explicit srcset URLs or a width=auto mode that selects a width from one URL (features, responsive delivery).
<img
src="https://cdn.example.test/cdn-cgi/image/width=800,quality=75,format=auto/hero.jpg"
srcset="
https://cdn.example.test/cdn-cgi/image/width=480,quality=75,format=auto/hero.jpg 480w,
https://cdn.example.test/cdn-cgi/image/width=800,quality=75,format=auto/hero.jpg 800w,
https://cdn.example.test/cdn-cgi/image/width=1280,quality=75,format=auto/hero.jpg 1280w"
sizes="100vw"
width="1280"
height="720"
alt="Mountain trail"
/>
Use client hints such as viewport width, device pixel ratio and Save-Data only when your service supports them and you understand cache variation. An explicit, bounded width list is easier to reason about and prevents a cache key for every possible pixel value.
Upload normalization and personalized compositions
Normalize user uploads before delivery: apply EXIF orientation, normalize ICC color metadata, strip unnecessary metadata, enforce maximum dimensions and record the original. Generate thumbnails and focal-point crops from the normalized master. For campaigns or user profiles, compose a background, subject and text layer in a controlled server-side pipeline, then cache the resulting immutable asset.
A practical pipeline is:
- Validate type, dimensions and file size.
- Decode and normalize orientation and color.
- Store an immutable original outside the public path.
- Generate bounded derivatives or allow a constrained transformation URL.
- Set immutable caching for versioned outputs.
- Delete or replace derivatives when the source version changes.
AWS documents automatic optimization and migration patterns for CloudFront in its dynamic image transformation use cases.
Layout, loading and accessibility
- Set
widthandheight, or an equivalentaspect-ratio, so the browser reserves space and reduces layout movement. - Use
loading="lazy"for below-the-fold images. Do not lazy-load the likely Largest Contentful Paint image; give that image appropriate priority. - Use meaningful
alttext for informative images and emptyaltfor decorative ones. - Use
decoding="async"where asynchronous decoding is appropriate. - Preconnect to a cross-origin image CDN only when it is needed; proxying through the primary origin can avoid an extra connection setup.
Measure Largest Contentful Paint, transferred bytes, cache hit ratio, transformation errors and origin latency. web.dev covers responsive image performance and layout stability.
Caching, keys and invalidation
Each unique source plus transformation parameter set can become an edge cache entry. Avoid needless one-pixel widths, unconstrained quality values and inconsistent parameter ordering. Normalize parameters at your application boundary and choose a finite width and quality policy.
| Decision | Recommended practice |
|---|---|
| Cache key | Include source version and only meaningful transformation fields. |
| Source updates | Use versioned filenames or a purge mechanism. |
| Quality | Offer a small set such as 60, 75 and 85 instead of arbitrary values. |
| Widths | Use a bounded ladder matched to real layout slots. |
| Private images | Use signed URLs and short TTLs; never expose unrestricted source access. |
Google Cloud notes that parameter order can be normalized for cache keys and that one invalidation can purge a base image and generated variants (details).
Security, reliability and cost controls
- Allow transformations only for approved source IDs or signed requests.
- Clamp width, height, pixel count, quality and output formats.
- Reject decompression bombs, oversized animated files and unsupported codecs.
- Protect expensive effects and PDF-like rasterization behind authentication or rate limits.
- Return a stable fallback image when a transformation fails, and log the source, parameters and error.
- Track origin response status: Google Cloud’s image optimization requires supported content types and successful HTTP 200 origin responses.
- Budget for storage, transformation operations, CDN egress and cache misses. More variants can improve bytes transferred while increasing storage and invalidation work.
Choosing an approach
| Approach | Best fit | Trade-offs |
|---|---|---|
srcset/picture |
Stable files and browser-controlled selection | You author and store variants; limited runtime crops |
| Application service | Business-specific composition and access rules | You operate workers, queues, storage and cache policy |
| Image CDN | Many sources, on-demand variants and global delivery | Vendor pricing, cache cardinality and migration effort |
| Hybrid | CDN for common transforms, application jobs for heavy compositions | Two systems and more observability work |
Compare browser control, art direction, format support, bandwidth, latency, cache-key cardinality, invalidation, transformation flexibility, signed-request controls, observability, price and vendor lock-in. web.dev recommends considering cost, support, documentation and migration effort when selecting an image CDN (guide).
Or skip the browser setup
If your goal is to capture a rendered page or image preview rather than build an image transformation pipeline, ScreenshotNeo returns a clean PNG, JPEG, WebP or PDF from one GET request. See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Before capture, cookie and consent banners are accepted and 60+ known consent platforms, newsletter popups and chat widgets are removed; each step can be turned off. Bot checks, blank pages, timeouts, failed loads and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
Troubleshooting dynamic images
The browser downloads the largest file
Check that width descriptors have w units, that sizes matches the actual slot, and that CSS is not forcing a larger rendered width. Inspect the selected request in browser developer tools.
Images look blurry on high-density screens
Provide sufficiently large candidates or pixel-density variants. Do not use a low maximum width when the slot can render at two device pixels per CSS pixel.
The crop removes the subject
Use a focal point or an explicit crop rectangle. Confirm whether your service crops before resizing; operation order changes composition.
Cache size grows without bound
Constrain widths, quality values and effects; normalize parameter order; remove client-specific values from cache keys unless required.
New uploads show old pixels
Version the source URL or purge the base image and generated variants. Check browser, CDN and origin cache headers.
Images cause layout shifts
Add intrinsic dimensions or aspect-ratio before the request completes. Reserve the final slot size even when the image is lazy-loaded.
CDN requests are slow on first view
Expect a transformation and origin fetch on a cold miss. Pre-generate critical derivatives, warm popular variants, or proxy through the primary origin and preconnect where appropriate.
Transformation requests fail
Check source status, content type, pixel limits, signed URL expiry and supported output formats. Log the complete normalized transformation request and return a known fallback.
FAQ
Are dynamic images the same as responsive images?
Responsive images are one form of dynamic delivery: the browser selects among sources. Server and CDN transformations generate or modify the bytes at request time.
Should every image use an image CDN?
No. A small site with a few stable assets may only need authored variants and srcset. A CDN becomes more useful when you have many originals, dimensions, crops or regions.
Does WebP or AVIF always win?
No. Compare visual quality, decode cost, browser support and actual transfer size. Use format negotiation with a fallback.
How many responsive widths should I create?
Choose a finite ladder based on real layout slots and device sizes. Extra near-duplicate widths increase cache entries without reliably improving output.
How do I protect private dynamic images?
Require signed URLs or authenticated transformation requests, constrain parameters and keep private sources outside public storage paths.
What should I monitor?
Track Largest Contentful Paint, transferred bytes, cache hits and misses, transformation latency, origin errors, fallback rate and invalidation success.


