Workflow

Image processing pipeline

How each photo becomes JPEG, WebP, and AVIF at multiple sizes, each with the smallest file size that still looks right.

Getting photos to look good and load fast is challenging. I’m picky about image quality, but I also don’t want images taking long to load, especially on slower connections.

And I’ve been through some rabbit holes trying to find the right balance between visual fidelity and file size. I could have offloaded this to an image hosting service, but I wanted full control without the cost.

At first, I used the same compression settings for every photo. That didn’t work well. I noticed detailed shots needed higher quality to avoid artifacts, while simple compositions could be compressed more without anyone noticing. Some files ended up unnecessarily large, others lost too much quality.

Manually fine-tuning the quality settings per image per resolution per format is impractical. So I built a pipeline that handles it for me, using SSIMULACRA2, a perceptual quality metric that scores how closely a compressed image matches a reference image.

How it works #

Each photo goes through the pipeline and comes out in three formats: JPEG, WebP, and AVIF, at multiple sizes, typically from 480px to 2560px on the long edge. Each format at each size is what I call a variant.

Original
The edited photo
Downscale
To multiple sizes, with libvips
Lossless PNG
One per size
JPEG encoder
mozjpeg
SSIMULACRA2
Against the PNG
JPEG variant
One per size
WebP encoder
cwebp
SSIMULACRA2
Against the PNG
WebP variant
One per size
AVIF encoder
avifenc
SSIMULACRA2
Against the PNG
AVIF variant
One per size

The downscaling and colour profile conversion to sRGB are handled by libvips, which produces a lossless PNG for each size. That PNG is what all three encoders start from.

Each encoder has a quality setting. The higher the quality, the larger the file size, and the same setting can look very different from one photo to another. So a binary search looks for the lowest setting that still reaches a target SSIMULACRA2 score. Every attempt is scored against the PNG by libjxl’s ssimulacra2 tool.

I usually aim at a perceptual score of 80, which I found to balance file size and visual fidelity for my photos. This is how the SSIMULACRA2 authors describe the scale considering comparisons made by an average observer, at 1:1, from a normal viewing distance:

ScoreQualityDistortion
NegativeExtremely lowVery strong distortion
10Very lowVery obvious and annoying artifacts
30LowObvious and annoying artifacts
50MediumSlightly annoying artifacts
70HighBarely noticeable in a side-by-side comparison
80Very highNot noticeable in a side-by-side comparison
85ExcellentNot noticeable in an in-place comparison
90Visually losslessNot noticeable in a flicker test
100Mathematically losslessIdentical to the original
Show the codeHide the code

This is a simplified version of my pipeline. If you are on a Mac, you can install the tools with Homebrew, save the script as pipeline.py, and run it on a photo. It writes every variant to a variants folder and prints the quality each one needed.

brew install vips mozjpeg webp libavif jpeg-xl
python3 pipeline.py photo.jpg
"""
A simplified version of my image pipeline. It turns a photo into JPEG,
WebP, and AVIF files at several sizes, each at the lowest quality that
still scores 80 or more on SSIMULACRA2.

Install the tools with Homebrew and run it on a photo like this.

    brew install vips mozjpeg webp libavif jpeg-xl
    python3 pipeline.py photo.jpg
"""
import subprocess
import sys
import tempfile
from pathlib import Path

# The long edge of each size, in pixels
SIZES = [480, 960, 1440, 1920, 2560]

# The SSIMULACRA2 score every file must reach
TARGET_SCORE = 80

# Each format with the range of quality settings to search
FORMATS = [('jpg',  75, 95), 
           ('webp', 75, 95), 
           ('avif', 50, 95)]

# Homebrew doesn't put mozjpeg's cjpeg on the PATH
CJPEG = '/opt/homebrew/opt/mozjpeg/bin/cjpeg'


def run(*args):
    """Runs a command line tool and returns what it prints. If the tool
    fails, the script stops with an error. The progress messages some
    tools print are hidden."""
    return subprocess.check_output(
        args, stderr=subprocess.DEVNULL, text=True)


def encode(png, out, quality):
    """Encodes the PNG at the given quality. The extension of out
    decides the format and so the encoder."""
    q = str(quality)
    if out.suffix == '.jpg':
        # -sample 1x1 keeps full colour detail
        run(CJPEG, '-quality', q, '-sample', '1x1', '-outfile', out, png)
    elif out.suffix == '.webp':
        run('cwebp', '-q', q, png, '-o', out)
    else:
        # -y 444 keeps full colour detail
        # -d 10 uses 10 bits per channel
        run('avifenc', '-q', q, '-y', '444', '-d', '10', png, out)


def score(png, image):
    """Compares an encoded image with the PNG it came from and returns
    its SSIMULACRA2 score. 100 means identical, and 80 means the
    difference isn't noticeable when the two are shown side by side."""
    # ssimulacra2 can't read WebP or AVIF, so decode those to a PNG first
    if image.suffix != '.jpg':
        decoded = png.with_name('decoded.png')
        run('vips', 'copy', image, decoded)
        image = decoded
    return float(run('ssimulacra2', png, image))


def find_lowest_quality(png, out, low, high):
    """Finds the lowest quality between low and high that still reaches
    the target score, and leaves out encoded at that quality.

    It's a binary search. Each attempt tries the quality halfway between
    low and high and halves the range that's left, so 75 to 95 takes at
    most five attempts instead of 21."""
    best = high
    while low <= high:
        mid = (low + high) // 2
        encode(png, out, mid)
        if score(png, out) >= TARGET_SCORE:
            # Good enough. Remember it and look for a lower quality.
            best, high = mid, mid - 1
        else:
            # Not good enough. Look for a higher quality.
            low = mid + 1

    # The last attempt may not be the best one, so encode the best again
    encode(png, out, best)
    return best


# The photo to process comes from the command line, and the variants go
# to a variants folder next to where the script runs
photo = Path(sys.argv[1])
Path('variants').mkdir(exist_ok=True)

# The PNGs go to a temporary folder that's deleted at the end
with tempfile.TemporaryDirectory() as tmp:
    for size in SIZES:
        # Downscale to a lossless PNG in sRGB, never upscaling. Every
        # encoder starts from it and is scored against it.
        png = Path(tmp) / f'{size}.png'
        run('vips', 'thumbnail', photo, png, str(size),
            '--size', 'down', '--output-profile', 'srgb')

        # Then each format, at the lowest quality that's good enough
        for ext, low, high in FORMATS:
            out = Path('variants') / f'{photo.stem}-{size}.{ext}'
            quality = find_lowest_quality(png, out, low, high)
            print(f'{out.name}: quality {quality}')

Settings #

These are the settings I use for each format, including the quality range the search stays within:

FormatEncoderQuality rangeChromaBit depth
JPEGmozjpeg75 to 954:4:48-bit
WebPcwebp75 to 954:2:08-bit
AVIFavifenc50 to 954:4:410-bit

The quality numbers don’t mean the same thing across encoders.

JPEG and AVIF keep full colour detail (4:4:4). Lossy WebP stores colour at a lower resolution than the image itself (4:2:0).

Lossless WebP keeps full colour detail (4:4:4), but its files are many times larger than lossy WebP, so I don’t use it.

Results #

The chart below has the details of some real photos I processed for this site. Note how the SSIMULACRA2 score stays close to the target, while the quality setting it takes to get there changes from photo to photo and from size to size.

15 variants, 2.13 MB in total, from a 26.1 MB original
JPEG
879.6 KB
mozjpeg 4.1.5
50607080901002260127228443KBScoreQuality480960144019202560
WebP
788.2 KB
cwebp 1.6.0
5060708090100123679179481KBScoreQuality480960144019202560
AVIF
458.2 KB
avifenc 1.4.1
506070809010021314685275KBScoreQuality480960144019202560

AVIF isn’t always smaller. With my photos, WebP usually wins at 480px, the smallest variant I aim for. From 960px up, AVIF usually wins.

My own encoding settings are probably part of why AVIF loses at small sizes. I’ve also noticed WebP can show banding in clear blue skies, so I skip WebP for those photos.

Publishing #

After processing, the variants are pushed to Cloudflare R2 and the metadata goes to the website’s GitHub repository.

Colours
Extracted with colorthief-cli
Variants
JPEG, WebP, and AVIF with hashed file names
Metadata
YAML files
Image storage
Cloudflare R2
Repository
GitHub
Site build
Hugo on Cloudflare Pages
Browser
The page comes from Cloudflare Pages and the photos from R2

As part of the image processing, the dominant colour and palette are extracted from each image using colorthief-cli. I have yet to find a use for the colour palette, but I like to have it available.

Cloudflare and browsers can cache the variants for a long time. Each file name includes a hash of the file, so if an image is ever reprocessed, it gets a new file name and the old cached copy is never used.

The metadata for each processed image (file names, hashes, formats, dominant colour and palette, SSIMULACRA2 score, encoder versions, encoding parameters, dimensions, and more) is stored in YAML files. On every push, Cloudflare Pages builds the site with Hugo, which reads the YAML to generate the gallery pages.

When you open a gallery, the browser picks the best format and size of each image for your screen. AVIF comes first, with WebP and then JPEG as fallbacks. While images load, the gallery shows each photo’s dominant colour as a placeholder, and each image fades in when it’s ready.

I’ve created custom layouts for displaying the photos.