Sub topic 13
Choosing Formats and Compression
This chapter assumes you know the img element, basic CSS sizing, and how srcset and sizes work from the previous chapter. Here you decide which file format to serve and how much to compress it.
Why format and compression matter
Photos are usually the heaviest assets on a page. A hero image can outweigh all the HTML, CSS, and JavaScript combined. Smaller files load faster, cost less bandwidth, and help the largest visible element appear sooner.
Two separate choices control file size:
- Format is the container and the compression method, such as JPEG or WebP.
- Compression settings are how hard you squeeze within that format, usually a quality value.
Resizing comes first. A 4000px-wide image shown at 800px wastes bytes in any format. Use srcset to serve sensible dimensions, then tune format and quality.
Lossy and lossless compression
Lossy compression discards detail that people notice least. Output is much smaller, but you cannot recover what was removed. Photos suit lossy compression because they contain smooth gradients and noise.
Lossless compression stores every pixel exactly. The file is larger, but nothing changes. It suits screenshots, logos, and images with flat color and sharp edges.
Re-saving a lossy file as lossy again removes more detail each time. This is called generation loss. Keep an original master file, and export each web version from it.
Formats compared
| Format | Compression | Transparency | Typical use | Support |
|---|---|---|---|---|
| JPEG | Lossy | No | Photos, universal fallback | All browsers |
| PNG | Lossless | Yes | Screenshots, graphics with sharp edges | All browsers |
| WebP | Lossy or lossless | Yes | Photos and graphics, general default | All current browsers |
| AVIF | Lossy or lossless | Yes | Photos where smallest size matters | Current major browsers |
| GIF | Lossless, 256 colors | Limited | Rarely a good choice for photos | All browsers |
Practical guidance:
- JPEG is the safe baseline. Every browser, email client, and tool reads it.
- WebP is usually 25 to 35 percent smaller than JPEG at similar visual quality. It is a good default for modern sites.
- AVIF often beats WebP on size, especially for smooth areas and low bitrates. Encoding is slower, and very fine texture can look soft at aggressive settings.
- PNG is a poor choice for photographs. A photo saved as PNG is often several times larger than the same photo as JPEG.
These percentages are rules of thumb. Results depend on the image, so compare your own files.
Choosing a quality setting
Quality is a number, usually 0 to 100. The scale differs between encoders, so a JPEG at 80 and an AVIF at 80 do not look the same. Compare by eye, not by number.
Starting points for photos:
- JPEG: quality 75 to 85.
- WebP: quality 75 to 80.
- AVIF: quality 50 to 65.
Then adjust per image:
- Zoom to 100 percent and inspect faces, text in the scene, and smooth gradients such as sky. These show artifacts first.
- Look for blocky squares, banding in gradients, and smeared fine detail.
- Lower quality until you notice damage, then step back up a little.
Images with noise, foliage, or fine fabric need higher quality or the texture turns to mush. Soft-focus backgrounds tolerate more compression.
If an image will carry overlaid text or sit behind a gradient, artifacts near the text are more visible. Check those regions specifically.
Serving modern formats with a fallback
The picture element lets the browser choose the first format it supports. Order sources from newest to oldest, and keep a universal img fallback last.
<picture>
<source type="image/avif" srcset="team-400.avif 400w, team-800.avif 800w, team-1600.avif 1600w" sizes="(min-width: 960px) 50vw, 100vw">
<source type="image/webp" srcset="team-400.webp 400w, team-800.webp 800w, team-1600.webp 1600w" sizes="(min-width: 960px) 50vw, 100vw">
<img
src="team-800.jpg"
srcset="team-400.jpg 400w, team-800.jpg 800w, team-1600.jpg 1600w"
sizes="(min-width: 960px) 50vw, 100vw"
width="800" height="600"
alt="Four colleagues around a whiteboard">
</picture>The type attribute lets the browser skip a source without downloading it. The width, height, alt, and styling all belong on the img. The picture and source elements only supply candidates.
This pattern multiplies files: three formats times three widths is nine files per photo. Use a build tool or image service to generate them rather than exporting by hand.
Generating the files
Command-line tools and build plugins do this well. This script uses the Python Pillow library to export WebP and JPEG at several widths from one master. AVIF output needs a Pillow build with AVIF support, or another encoder, so it is left out here.
from pathlib import Path
from PIL import Image
WIDTHS = [400, 800, 1600]
MASTER = Path("team-master.jpg")
OUT = Path("out")
OUT.mkdir(exist_ok=True)
with Image.open(MASTER) as master:
master = master.convert("RGB")
for width in WIDTHS:
if width > master.width:
continue # never upscale
height = round(master.height * width / master.width)
resized = master.resize((width, height), Image.LANCZOS)
stem = f"team-{width}"
resized.save(OUT / f"{stem}.jpg", quality=80, optimize=True, progressive=True)
resized.save(OUT / f"{stem}.webp", quality=78, method=6)
print(f"wrote {stem}.jpg and {stem}.webp ({width}x{height})")Note the guard against upscaling. Enlarging a small master adds bytes but no detail.
Metadata, color, and progressive loading
- Metadata. Cameras embed EXIF data such as device model, date, and sometimes GPS location. Strip it from web exports. It adds bytes and can expose where a photo was taken. Keep the orientation information applied correctly before stripping, or rotated photos will display sideways.
- Color profile. Convert to sRGB for the web. Wide-gamut profiles such as Display P3 can look dull or shifted in software that ignores profiles.
- Progressive JPEG. A progressive file shows a rough full image first and sharpens as data arrives. It is often slightly smaller than a baseline JPEG for larger photos.
Common errors
- Saving photos as PNG. The file is huge with no visible gain. Use JPEG, WebP, or AVIF.
- Saving flat graphics as lossy. Logos and screenshots get ringing artifacts around edges. Use PNG, lossless WebP, or SVG for vector artwork.
- Compressing an already compressed file. Always export from the master.
- Using one quality number everywhere. A portrait and a forest need different settings.
- Serving AVIF or WebP with no fallback. Older browsers show a broken image. Keep the
imgwith a JPEGsrc. - Missing
widthandheight. The format work is wasted if the page still shifts when the image arrives. Declare dimensions on theimg, as covered in the layout shift chapter. - Lazy-loading the hero image. Add
loading="lazy"to images below the fold only. The main image at the top should load immediately. - Trusting file size alone. A small file that looks damaged hurts the page more than it helps.
A simple decision process
- Start from the original master at full resolution.
- Crop and resize to the dimensions you need, including the
srcsetwidths. - Choose the format: AVIF and WebP with a JPEG fallback for photos, PNG or SVG for flat graphics.
- Export at the starting quality, inspect at 100 percent, and adjust.
- Strip metadata and convert to sRGB.
- Check the final weight. A common budget for a content image is under about 150 KB at its largest displayed size, and a hero image somewhat more. Treat these as targets, not laws.
Summary
Resize first, then pick a format. Use AVIF or WebP for photos with a JPEG fallback, and keep PNG or SVG for flat graphics. Set quality by looking at the result, not by trusting a number. Always export from a master, strip metadata, and keep width and height on the img.
Exercise
A page has a 3200px-wide photo of a crowded market, saved as PNG at 2.4 MB, displayed at 800px wide. Describe the steps you would take to reduce its weight without visible damage, and write the picture markup structure that delivers it safely to older browsers.
Show answer
Start from the original master, not the PNG, if one exists. Resize to the needed widths (for example 400, 800, and 1600) instead of serving 3200px. Export as AVIF and WebP, plus a JPEG fallback, because a busy photo suits lossy compression and PNG is wasteful for photos. Begin near quality 80 for JPEG, 78 for WebP, and 55 for AVIF, then inspect at 100 percent. Busy detail may need slightly higher quality. Strip metadata and convert to sRGB. In markup, use a picture element with a source type="image/avif" and a source type="image/webp", each with srcset and sizes, followed by an img with a JPEG src, srcset, sizes, width, height, and alt text.
Exercise
Why can a quality value of 80 give different results in JPEG and AVIF, and how should you pick a value instead?
Show answer
Each encoder defines its own quality scale, so the same number does not mean the same visual result or file size. Pick a value by exporting at a starting point for the format, viewing the result at 100 percent, checking faces, gradients, and fine texture for artifacts, and lowering quality until damage appears, then stepping back up slightly.