ScreenshotNeo

BlogHow-to

How to Compress Images for the Web and Improve Page Speed

Reduce image bytes without sacrificing useful detail. Learn how to resize, choose formats, serve responsive images, and measure page speed improvements.

By the ScreenshotNeo team4 October 20269 min read

To compress images for the web, first resize each source to the pixel dimensions your page actually needs, then compare lossy and lossless encodings at visually acceptable quality. Serve a small set of responsive candidates so each device downloads a suitable file, and measure the page again. Smaller image files reduce transfer bytes, but they do not guarantee a faster page if another resource, server delay, or rendering work is the bottleneck.

This guide covers a repeatable command-line workflow, responsive HTML, format selection, quality checks, performance measurement, and common problems. The example commands use cwebp, Google’s WebP encoder. Its options and availability can vary by installed version; consult the official cwebp documentation. For broader guidance on image sizing, encoding, and quality, see web.dev’s image performance guide.

1. Find the images that matter

Start with images that are large in bytes or pixel dimensions, especially those visible near the top of the page or likely to be the Largest Contentful Paint (LCP) element. An off-screen decorative image is less likely to affect the first visible render. Use browser developer tools to inspect transferred resources and the page waterfall, and identify which image is displayed at what size.

  1. Record each candidate’s file size and intrinsic pixel dimensions.
  2. Compare those dimensions with the image’s rendered width and height at common viewport sizes.
  3. Check whether the image is the page’s likely LCP element, appears above the fold, or is requested early.
  4. Prioritize assets where you can reduce needless pixels or bytes without harming their visual role.

Do not infer a page-speed gain from file size alone. Image optimization can help LCP when the image is on the critical path, but the result also depends on priority, delivery, and the rest of the page. See web.dev’s LCP guidance.

2. Resize images to fit the layout

Compression cannot compensate for dimensions that are far larger than necessary. If a page displays an image at about 700 CSS pixels wide, serving a 3000-pixel-wide original to every device may transfer many unused pixels. But shrinking everything to the CSS width can look blurry on high-density screens. Generate candidates for the actual layout and account for higher-density displays.

For example, if a content image is displayed at 700 CSS pixels, you might produce candidates around 700 pixels and 1400 pixels wide for standard and higher-density displays. Those are illustrative values: choose widths from your page layout and audience, preserve the source aspect ratio, and check the result on the devices you support.

Keep the candidate set manageable. A few useful widths are easier to generate, cache, and maintain than many near-duplicates. Revisit the set if your layout or measured device mix changes.

3. Choose a format and compression level

There is no single best format or quality setting for every asset. Compare the output bytes and visual quality for representative images from your site.

Choice Useful when Check
Lossy compression Reducing photo size while accepting some discarded image information Inspect for artifacts at the size people will see.
Lossless compression Preserving image data exactly is important Expect different size tradeoffs than lossy encoding.
WebP You want a modern web format with lossy and lossless modes Test your actual images and target browsers. Google documents WebP as supporting both compression modes.
AVIF You want to evaluate another modern format that may be efficient for some images Compare the same quality target and confirm browser support for your audience; retain a fallback if needed.
JPEG or PNG You need an existing or fallback format suited to the asset and delivery requirements Do not assume either is always larger or smaller than a modern alternative.

WebP’s compression results are not a guarantee that it will beat every alternative on every image. AVIF can be more efficient for some inputs, but results depend on image content, encoder, quality target, and browser support. Compare like with like, and check edges, lettering, logos, line art, and colored text on flat backgrounds especially carefully. Lossy compression can make these details look poor before a photograph does.

For manual compression, web.dev lists Squoosh and ImageOptim. Google’s cwebp utility is another option for creating WebP files. Hosted services can automate transformations and delivery; Cloudflare documents image compression, responsive transformations, modern format delivery, and lazy loading in its image optimization documentation. Choose a workflow that fits your build and delivery setup, then inspect its output rather than relying on a promised setting.

4. Convert a file with cwebp

Install a suitable cwebp build for your operating system using Google’s official WebP documentation. Then convert a photo from the terminal:

cwebp -q 80 input.jpg -o output.webp

-q 80 is an example quality setting for lossy encoding, not a universal recommendation. Try several values on real assets, compare the resulting file sizes, and inspect the images at their display size. A quick shell loop can create a few candidates for visual review:

for quality in 70 80 90; do
  cwebp -q "$quality" input.jpg -o "output-q${quality}.webp"
done

For an image where pixel preservation matters, check the installed cwebp version’s lossless options in the official documentation instead of using the lossy example. Keep the source file until you have checked the converted output and confirmed the build or publishing pipeline can serve it correctly.

5. Serve responsive candidates

Use srcset and sizes when the same image has multiple widths. The browser uses the candidate list and the rendered slot information to select a resource appropriate to the viewport and pixel density.

<img
  src="/images/article-700.webp"
  srcset="/images/article-700.webp 700w,
          /images/article-1400.webp 1400w"
  sizes="(max-width: 720px) 100vw, 700px"
  width="700"
  height="466"
  alt="A descriptive alternative for the image">

Update the example paths, dimensions, and sizes rule to match your generated files and actual layout. Providing width and height helps the browser reserve the image’s aspect ratio while it loads. Verify in developer tools which candidate the browser requests at representative viewport widths and device pixel ratios.

To offer AVIF where supported and WebP as a fallback, use <picture> with sources in preference order:

<picture>
  <source
    type="image/avif"
    srcset="/images/article-700.avif 700w,
            /images/article-1400.avif 1400w"
    sizes="(max-width: 720px) 100vw, 700px">
  <source
    type="image/webp"
    srcset="/images/article-700.webp 700w,
            /images/article-1400.webp 1400w"
    sizes="(max-width: 720px) 100vw, 700px">
  <img
    src="/images/article-700.jpg"
    srcset="/images/article-700.jpg 700w,
            /images/article-1400.jpg 1400w"
    sizes="(max-width: 720px) 100vw, 700px"
    width="700"
    height="466"
    alt="A descriptive alternative for the image">
</picture>

Keep each format’s candidate dimensions aligned. An alternative is content negotiation based on the request’s Accept header. If a response varies according to that header, the cited web.dev guidance says to send Vary: Accept so shared caches distinguish representations.

6. Check loading behavior and measure again

After deploying the new assets, check both the files and the page:

  • Confirm the browser loads the expected format and responsive width.
  • Inspect the image at its actual rendered size, including high-density screens where relevant.
  • Check the network waterfall for transferred bytes, request timing, and whether the likely LCP image is discovered and prioritized.
  • Compare lab measurements before and after under comparable conditions, and review field measurements where available.
  • Look for regressions such as blurry images, layout shifts, broken paths, or cache entries serving the wrong format.

Do not lazy-load an above-the-fold hero or likely LCP image by default. Lazy loading is useful for off-screen images, but delaying an important early image can work against LCP. If the likely LCP image needs a higher fetch priority, consider doing so selectively and verify its request priority and measured results; avoid adding priority hints indiscriminately.

Or skip the browser setup

If you need a screenshot of the finished page to review image quality or document the result, ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request can return a PNG, JPEG, WebP, or PDF; see the ScreenshotNeo API documentation for the available parameters.

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}`);

ScreenshotNeo accepts cookie and consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the capture; each cleanup step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card.

Troubleshooting

Symptom Likely cause Fix
The image looks blurry The candidate is too small for its rendered size or pixel density, or the lossy setting is too aggressive. Generate a larger candidate, test a higher quality level, and verify that srcset includes suitable widths.
Text or edges look smeared Lossy compression is damaging sharp boundaries or flat-color details. Try a less aggressive setting or lossless encoding, then inspect the image at actual display size.
The browser always downloads the largest candidate The sizes value or width descriptors do not reflect the rendered layout, or the viewport and density make that candidate appropriate. Correct the slot-width rule, check candidate descriptors, and inspect the actual request in developer tools.
The fallback image does not appear A source path is incorrect, a declared type does not match the file, or the fallback markup is missing or broken. Check each URL and MIME type, then test in a browser that does not support the preferred source format.
A cache serves the wrong format Negotiated image responses may be cached without distinguishing the request’s accepted formats. When the response varies on Accept, configure Vary: Accept and verify the cache behavior.
The page is not faster after compression The image may not be the bottleneck, may not be on the critical path, or another delay may dominate. Review the waterfall and LCP element, confirm the new file is actually served, and compare page measurements under similar conditions.
LCP got worse after adding lazy loading The likely LCP image may have been delayed. Remove lazy loading from the early, important image; use lazy loading for appropriate off-screen images and remeasure.

Performance, reliability, and cost considerations

  • Build time and storage: Every extra width and format variant adds files to generate, store, cache, and maintain. Produce candidates that serve real layout needs.
  • Visual reliability: Keep originals and inspect representative outputs after changing encoders or settings. A setting that works for photographs may fail for text-heavy graphics.
  • Delivery reliability: Test fallback paths, content types, cache keys, and responsive selection. If using format negotiation, account for the accepted format in shared caching.
  • Performance validation: Compare page-level results, not just encoded file sizes. A smaller image can still arrive late or have little effect if another resource dominates.
  • Cost: Manual conversion tools and build-time transformations require engineering and maintenance time. Hosted optimization can automate delivery; compare its current plan terms and capabilities against your traffic and workflow before adopting it. This guide makes no price or savings claims for third-party services.

FAQ

Should I convert every image to AVIF?

No universal format wins for every image and browser audience. Compare AVIF with WebP and any necessary fallback using your real assets and quality requirements.

Does a smaller file always mean a faster page?

No. Fewer bytes can reduce transfer work, but the image must matter to the page’s loading path, and other resources or delays may dominate.

How many responsive widths should I generate?

Use a manageable set that corresponds to real layout sizes and device needs. Verify what browsers select, then adjust based on observed behavior.

What quality setting should I use?

There is no setting that suits all images. Compare output size and visual artifacts at the actual display size, especially around text, logos, and sharp edges.