How to Convert and Compress Images to WebP for a Faster Website

Convert website images to WebP, compare quality and file size, and serve the right dimensions. Use Squoosh, cwebp or a reusable Sharp script.

The BuildVerse team8 min read

A large photo file shrinking into a smaller WebP file, with a speedometer rising beside it.

This guide is for site owners and developers whose pages load slowly because of their pictures. You will convert JPEG and PNG files to WebP, size them for the places they appear, and check the result with tools every browser already has.

Choose dimensions before compression. For an image displayed 800 CSS pixels wide, a 1600 pixel file can serve a screen with a device pixel ratio of 2. Export smaller candidates too, and let the browser choose. Avoid resizing every image to the same width.

At the end you will have WebP files at a few widths, an img or picture element that picks the right one, width and height on every image, and a Lighthouse run that shows the result.

Before you start

  • A folder of still JPEG or PNG originals. Keep these separately; export new versions from them.
  • A desktop browser for Squoosh at squoosh.app. No account is required. Images are processed locally; its README discloses analytics, including before and after file sizes.
  • For cwebp: Google’s libwebp 1.6.0 download matching your operating system and CPU. The folder loop below requires Bash, including Bash on Windows.
  • For Sharp: a supported Node.js LTS release and npm. Sharp requires a Node-API v9 runtime, such as Node.js 20.9.0 or later. Check with node -v.
  • For checks: Chrome for Desktop and access to edit and publish your site’s image references.

Documentation checked on 5 December 2026. The Sharp example pins 0.35.6, listed in its official changelog. Keep package-lock.json with your build configuration.

Which route should you pick

  • Squoosh, for a handful of images you can drag into a browser window.
  • cwebp, for a folder of images on your own computer, run from a terminal.
  • Sharp, for a build script that makes WebP files every time you deploy a site.

Route 1: Squoosh in the browser

  1. Open https://squoosh.app in a desktop browser.
  2. Drop one image onto the page.
  3. Enable Resize in the output panel, keep Maintain aspect ratio enabled, and enter the target Width. Do not exceed the original width.
  4. In the format list, choose WebP.
  5. For a photo, leave Lossless off and start with Quality at 75. Compare both sides of the preview at display size and zoom in on edges.
  6. For screenshots or small text, enable Lossless and leave Slight loss at 0. Compare its size with the original PNG.
  7. Read the new file size in the output panel and compare it with the original.
  8. Download the output. Name it with its actual width, such as hero-1600.webp, then repeat for smaller widths from the original.

Route 2: cwebp for a folder

  1. Download libwebp 1.6.0 from developers.google.com/speed/webp/download and unpack it.
  2. Add its bin folder to PATH so cwebp is available from your image project folder.
  3. Run cwebp -version and cwebp -h to check the installation.
  4. For the first command, use an upright hero.jpg at least 1600 pixels wide in originals.
  5. For a mixed-size folder, use the second example. It converts without resizing, so it cannot enlarge small inputs.
  6. Compare each output with its original. Keep the smaller acceptable version.
mkdir -p webp
cwebp -q 75 -resize 1600 0 originals/hero.jpg -o webp/hero-1600.webp
One photo, 1600 pixels wide, quality 75
mkdir -p webp
for f in originals/*; do
  [ -f "$f" ] || continue
  case "$f" in
    *.[jJ][pP][gG]|*.[jJ][pP][eE][gG]|*.[pP][nN][gG])
      name=${f##*/}
      cwebp -q 75 -metadata icc "$f" -o "webp/$name.webp" || break
      ;;
  esac
done
Bash: still JPEG and PNG files, original dimensions. Retaining the input extension avoids collisions such as photo.jpg and photo.png.

For small text, try lossless first. Near-lossless changes pixel values before lossless encoding, so it is not pixel-identical. The optional second command below uses Google’s suggested starting value of 60. Quality 100 alone does not select lossless mode.

cwebp -lossless screenshot.png -o screenshot-lossless.webp
cwebp -near_lossless 60 screenshot.png -o screenshot-near-lossless.webp
Compare lossless and near-lossless exports from the original screenshot.

Route 3: Sharp in a build script

  1. Open your site project folder. For a new empty project, run npm init -y first.
  2. Run npm install --save-exact sharp@0.35.6.
  3. Save build-images.mjs below beside originals. Use unique lowercase names such as hero.jpg and shop-front.png.
  4. Run node build-images.mjs from that folder. It writes WebP candidates and a fallback into public/images.
  5. Commit the output, or run the script as a build step, depending on how your site deploys.
npm install --save-exact sharp@0.35.6
import sharp from 'sharp';
import { mkdir, readdir } from 'node:fs/promises';
import { join, parse } from 'node:path';

const inputDir = 'originals';
const outputDir = 'public/images';
const widths = [480, 800, 1200, 1600];
const entries = await readdir(inputDir, { withFileTypes: true });
const files = entries.filter(e => e.isFile() && /\.(jpe?g|png)$/i.test(e.name));
if (!files.length) throw new Error('No JPEG or PNG files in originals');
const names = new Set();
for (const { name } of files) {
  const base = parse(name).name;
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(base) || names.has(base)) {
    throw new Error(`Use a unique lowercase, hyphenated basename: ${name}`);
  }
  names.add(base);
}
await mkdir(outputDir, { recursive: true });
for (const { name } of files) {
  const input = join(inputDir, name);
  const base = parse(name).name;
  const metadata = await sharp(input).metadata();
  if ((metadata.pages ?? 1) > 1) throw new Error(`Use a still image: ${name}`);
  const sourceWidth = metadata.autoOrient.width;
  const targets = [...new Set(widths.map(w => Math.min(w, sourceWidth)))];
  const isPng = /\.png$/i.test(name);
  for (const width of targets) {
    const info = await sharp(input)
      .autoOrient()
      .resize({ width, withoutEnlargement: true })
      .webp(isPng ? { lossless: true } : { quality: 75 })
      .toFile(join(outputDir, `${base}-${width}.webp`));
    console.log(`${base}-${info.width}.webp: ${info.width} x ${info.height}, ${info.size} bytes`);
  }
  const fallback = sharp(input).autoOrient()
    .resize({ width: Math.min(1200, sourceWidth), withoutEnlargement: true });
  await (isPng ? fallback.png() : fallback.jpeg({ quality: 85 }))
    .toFile(join(outputDir, `${base}-fallback.${isPng ? 'png' : 'jpg'}`));
}
build-images.mjs

The script uses EXIF orientation before resizing and caps each width at the source width. A 600 pixel original produces 480 and 600 pixel files, with no falsely labelled 1600 pixel candidate. PNG inputs use lossless WebP; for a photograph saved as PNG, you can change that choice to quality 75. Sharp’s WebP quality default is 80.

Worksheet: before and after sizes

Record measurements from your own exports. Compare formats at equal dimensions and acceptable visual quality; a resized WebP versus a full-size JPEG mixes two different savings.

Version               Dimensions       File size in bytes
Original              YOUR_WIDTH x YOUR_HEIGHT   ...
Resized JPEG or PNG    YOUR_WIDTH x YOUR_HEIGHT   ...
WebP, same dimensions YOUR_WIDTH x YOUR_HEIGHT   ...

Saving (%) = 100 × (original bytes - output bytes) / original bytes
Measurement worksheet, not benchmark results.

A smaller file is useful only if it still looks acceptable. Inspect faces, fine text, gradients and transparent edges. If WebP grows, adjust its settings or keep the original format.

Serve responsive sizes with srcset

Use srcset to offer several widths. Each w value must equal that file’s actual pixel width. This example assumes a 4:3 hero.jpg at least 1600 pixels wide. For smaller originals, remove missing candidates and use their real dimensions. Upload the output so these /images/ URLs resolve; public/images is a build convention, not a universal hosting path.

<img
  style="display: block; width: 100%; max-width: 800px; height: auto;"
  src="/images/hero-1200.webp"
  srcset="/images/hero-480.webp 480w, /images/hero-800.webp 800w, /images/hero-1200.webp 1200w, /images/hero-1600.webp 1600w"
  sizes="(max-width: 800px) 100vw, 800px"
  width="1600"
  height="1200"
  fetchpriority="high"
  alt="YOUR_ALT_TEXT_DESCRIBING_THE_PHOTO">
Responsive hero image with a WebP source set

The inline CSS caps display width at 800px. The sizes value assumes a full-viewport slot below that; adjust it for page gutters or narrower containers. Use picture if your target clients need a fallback. The script creates hero-fallback.jpg from hero.jpg; PNG inputs get a PNG fallback to retain transparency. Use either example, not both.

<picture>
  <source
    type="image/webp"
    srcset="/images/hero-480.webp 480w, /images/hero-800.webp 800w, /images/hero-1200.webp 1200w, /images/hero-1600.webp 1600w"
    sizes="(max-width: 800px) 100vw, 800px">
  <img
    style="display: block; width: 100%; max-width: 800px; height: auto;"
    src="/images/hero-fallback.jpg"
    width="1600"
    height="1200"
    fetchpriority="high"
    alt="YOUR_ALT_TEXT_DESCRIBING_THE_PHOTO">
</picture>
The same image with a picture element and a JPEG fallback

Set width, height and loading on every image

Include width and height on img so the browser can reserve space before download. Match the image’s aspect ratio and keep it consistent across candidates. Update the example’s 1600 by 1200 values for your own image.

Do not lazy-load an image visible in the initial viewport. Use fetchpriority="high" for the main image likely to be the Largest Contentful Paint element, and loading="lazy" for images further down the page.

Check that it worked

  1. Open the published page in Chrome and open DevTools.
  2. In Network, enable Disable cache, select the Img filter and reload.
  3. Open the image request. Confirm a successful response, the expected URL and Content-Type: image/webp. A CDN may intentionally serve another supported format.
  4. Check the downloaded image’s dimensions and the Size column. Compare file bytes at the same dimensions, rather than cached transfer sizes.
  5. Repeat at desktop and phone widths. Allow for device pixel ratio: a 400 CSS pixel slot at ratio 3 can legitimately select a 1200 pixel file.
  6. In Lighthouse, choose Analyze page load and Run audit. Read Improve image delivery; Lighthouse 13 merged the old sizing, encoding and modern-format audits into this insight.
  7. Compare repeated runs using the same viewport and throttling. Check image bytes and LCP as well as the score.
  8. Inspect the page visually for blur, sideways photos, changed colours and layout movement before publishing the remaining images.

Common mistakes and fixes

  • Renaming photo.jpg to photo.webp. Fix: encode it with one of these tools; changing the extension does not convert the file.
  • Blurry text. Fix: select Lossless in Squoosh, use cwebp -lossless, or keep the original PNG. Near-lossless still changes pixels.
  • Sideways phone photos. Fix: use the Sharp script’s autoOrient step, or export upright pixels from an editor before cwebp.
  • Changed colours after cwebp. Fix: preserve an existing ICC profile with -metadata icc, as the loop does. Metadata defaults to none; -metadata all also copies EXIF and XMP when supported, including potentially unwanted location data.
  • Large downloads on mobile. Fix: check actual candidate widths and sizes against the CSS layout and device pixel ratio.
  • WebP exists but the page still fetches JPEG. Fix: update the image URL in your HTML or CMS, deploy the files, and check whether a cache or image service is serving an older response.
  • Broken image URLs. Fix: open each URL directly and check the deployment folder and filename case. Keep old URLs working while replacing references.
  • Build output includes obsolete widths. Fix: remove stale generated candidates when originals change, and update markup to match current outputs.

Limits: when AVIF or SVG is better

WebP supports transparency and both lossy and lossless compression. These routes cover still JPEG and PNG inputs. For animation, use a dedicated workflow; cwebp does not support animated PNG or animated WebP input.

AVIF is another format to compare for photos. Measure file size, visual quality and encoding time for your assets. Keep logos and simple shapes as SVG when you have vector originals.

Keep important text in HTML so readers can select it and assistive tools can access it. Image conversion does not address other performance problems such as slow server responses or blocking scripts.

Questions people ask

Is WebP smaller than JPEG?

Often, at a similar visual quality. web.dev says WebP compresses better than JPEG and PNG. Your own files decide, so compare the sizes from your own export.

What quality setting should I use?

Start at 75 for photos. That is cwebp's default, and Sharp's default is 80. Lower the value only after you check the result at display size.

Should I keep my JPEG files?

Yes. Keep originals for future exports. Publish a JPEG or PNG fallback if your target clients need one.

Is AVIF better than WebP?

AVIF can offer smaller files for photos, but the result depends on the image and settings. Compare both at acceptable visual quality.

Sources

  1. Google Developers: cwebp reference (checked 5 Dec 2026)
  2. Google Developers: WebP downloads (checked 5 Dec 2026)
  3. Sharp: installation (checked 5 Dec 2026)
  4. Sharp: output options (checked 5 Dec 2026)
  5. Sharp: resizing (checked 5 Dec 2026)
  6. Sharp: input metadata (checked 5 Dec 2026)
  7. Sharp: image operations (checked 5 Dec 2026)
  8. Squoosh: app and project README (checked 5 Dec 2026)
  9. Squoosh: resize controls (checked 5 Dec 2026)
  10. Squoosh: WebP controls (checked 5 Dec 2026)
  11. web.dev: responsive images (checked 5 Dec 2026)
  12. WHATWG: embedded content (checked 5 Dec 2026)
  13. web.dev: layout shift (checked 5 Dec 2026)
  14. web.dev: lazy loading (checked 5 Dec 2026)
  15. web.dev: fetch priority (checked 5 Dec 2026)
  16. Chrome: Network panel (checked 5 Dec 2026)
  17. Chrome: Lighthouse overview (checked 5 Dec 2026)
  18. Chrome: retired image sizing audit (checked 5 Dec 2026)
  19. Chrome: Improve image delivery (checked 5 Dec 2026)
  20. web.dev: image formats (checked 5 Dec 2026)
  21. Google Developers: WebP FAQ (checked 5 Dec 2026)
  22. Node.js: file system (checked 5 Dec 2026)
  23. Node.js: path (checked 5 Dec 2026)
  24. GNU: Bash reference manual (checked 5 Dec 2026)

All guides