Darkroom

Image processing pipeline

How each photo is prepared for publishing.

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.

At first, I used the same compression settings for every photo. That didn’t work well. The same setting could look fine on one photo and show artifacts on another. Raising it until every photo looked right made most files larger than they needed to be.

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.

I could have offloaded all of this to an image hosting service, but I wanted full control without the cost or the vendor lock-in. I still depend on Cloudflare for hosting, but I own the files and how they’re generated.

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.

Encoders #

These are the encoders and settings I use for each format:

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. AVIF, for example, typically reaches the same SSIMULACRA2 score as JPEG and WebP at a lower quality value, which is why its range starts at 50.

JPEG and AVIF keep full colour detail (4:4:4). For WebP, I use lossy compression. It keeps the brightness of every pixel, but only one colour for each block of four pixels (4:2:0). The eye notices colour detail less than brightness, so this saves space, but it can soften sharp edges between strong colours. Lossless WebP keeps full colour detail, but its files are many times larger, so I don’t use it.

AVIF is the only one of the three that all browsers support at 10 bits per channel, so I encode it at 10 bits. It helps smooth gradients like clear skies.

Chroma subsampling #

Encoders store each pixel as a brightness value and two colour values. The eye picks up detail in brightness far better than in colour, so brightness is kept for every pixel, but colour can be kept at a lower resolution, with each colour sample shared by a few pixels.

The three numbers say how many colour samples are kept, measured on a block of pixels 4 wide and 2 rows high:

  • The first is the width of the block: 4 pixels.
  • The second is how many colour samples the first row keeps.
  • The third is how many new colour samples the second row adds. In 4:4:4 and 4:2:2 it adds as many as the first row, so each row has its own. In 4:2:0 it adds none, so the two rows share the same samples, and each one covers a 2×2 block.
4:4:4
4 in row 1 4 new in row 2
4 wide
Every pixel keeps its own colour, so the 8 pixels have 8.
4:2:2
2 in row 1 2 new in row 2
4 wide
Each pair of pixels side by side shares one colour, so the 8 pixels have 4.
4:2:0
2 in row 1 0 new in row 2
4 wide
Each 2×2 block shares one colour, so the 8 pixels have 2.

JPEG and AVIF can use any of the three. Lossy WebP always uses 4:2:0. Lossless WebP behaves like 4:4:4, but it doesn’t split brightness from colour at all. It stores each pixel’s red, green, and blue as they are.

This is what each one does to a small patch of pixels with a sharp edge between two colours:

The original pixels.
Their brightness, kept for every pixel by all three.
4:4:4 keeps every pixel’s colour.
So the result matches the original.
4:2:2 keeps one colour for each pair of pixels side by side, the average of the two.
So the pairs that cross the colour edge get a mixed colour, while the brightness edge stays sharp.
4:2:0 keeps one colour for each 2×2 block, the average of its four pixels.
So the mixed colour spreads over whole blocks.

This is a simplified picture. Encoders can do better than a plain average, and decoders smooth the colour when they scale it back up, so on screen the mixed colour looks softer than these blocks.

Bit depth #

A colour on screen is a mix of red, green, and blue, and each of the three is a channel. A pixel stores a level for each channel, which says how much of it there is. With 8 bits, a channel has 256 levels. With 10 bits, it has 1,024.

8‑bit 10‑bit Red112 449 Green155 622 Blue208 834
A sky blue as levels of red, green, and blue, out of 255 in 8‑bit and out of 1,023 in 10‑bit. The levels mark the same amounts, but 10‑bit has about three more levels between each pair of 8‑bit ones.

The encoders turn red, green, and blue into a brightness and two colour channels, as in the section above, with the same number of levels.

In a smooth gradient, like a clear sky, neighbouring pixels differ only slightly. Compression rounds those differences, and with fewer levels to round to, a gradient can break into visible bands. With more levels, each step is smaller and the bands are harder to see.

8‑bit4 steps 10‑bit16 steps
The same short stretch of a sky gradient, enlarged and with its steps exaggerated. Where 8‑bit has 4 steps, 10‑bit has 16, so each step is smaller and harder to see.

My originals, and the PNGs the encoders start from, are 8‑bit. Encoding AVIF at 10 bits still helps, because the encoder works with finer steps, so its own rounding adds less banding, even when the browser shows it at 8 bits. JPEG and WebP, as all browsers support them, are 8‑bit only.

Finding the quality setting #

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 within the format’s range 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

The search starts in the middle of the format’s quality range, and each attempt rules out half of what’s left: if it reaches 80, no higher quality is needed, and if it doesn’t, no lower one will do.

JPEG Keeps 86
75 80 85
Target Score Quality
50 60 70 80 90 95
WebP Keeps 90
75 80 85
Target Score Quality
50 60 70 80 90 95
AVIF Keeps 60
75 80 85
Target Score Quality
50 60 70 80 90 95
Each dot represents an attempt: the quality tried and the score it got. Filled dots reach the score 80 and hollow ones fall short. The shaded area is the quality range left to search, and the search keeps the lowest quality that reaches the score 80.

On my Mac, a photo typically takes about half a minute to be processed, with its variants encoded in parallel.

Show the codeHide the code

Here is the code for 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.
"""
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':
        run(CJPEG, '-quality', q,
            # Keep colour at full resolution. Otherwise mozjpeg
            # reduces it at lower qualities.
            '-sample', '1x1',
            # Tune for SSIM. This also resets the quantisation
            # table, so -quant-table has to come after it.
            '-tune-ssim',
            # Use the quantisation table tuned for MS-SSIM
            '-quant-table', '2',
            '-outfile', out, png)
    elif out.suffix == '.webp':
        run('cwebp', '-q', q,
            # The slowest method, which tries more options
            '-m', '6',
            # Sharper RGB to YUV conversion, so colour edges bleed
            # less at half colour resolution
            '-sharp_yuv',
            # Move bits from busy areas, where loss hides, to flat
            # ones like skies
            '-sns', '100',
            # Turn the deblocking filter off, to keep fine texture
            '-f', '0',
            png, '-o', out)
    elif out.suffix == '.avif':
        run('avifenc', '-q', q,
            # Slower than the default, for smaller files
            '-s', '3',
            # 10 bits per channel, which reduces banding
            '-d', '10',
            # Keep colour at full resolution
            '-y', '444',
            # Tune for still images, guided by SSIMULACRA2
            '-a', 'tune=iq',
            # Leave out the photo's metadata, as the JPEG and WebP
            # encoders do
            '--ignore-exif', '--ignore-xmp',
            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 side by side."""
    # ssimulacra2 can't read WebP or AVIF, so those become 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.
    If none does, it uses high.

    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, and 50 to 95 at
    most six instead of 46."""
    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 = mid
            high = mid - 1
        else:
            # Not good enough. Look for a higher quality.
            low = mid + 1

    # The last attempt may not be the best, 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 in linear light 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', '--linear', '--intent', 'perceptual',
            '--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}')

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.01 MB in total, from a 26.1 MB original
JPEG 879.6 KB
mozjpeg 4.1.5
50 60708090100
Score Quality
480960144019202560
KB2260127228443
WebP 783.9 KB
cwebp 1.6.0 −11%
50 60708090100
Score Quality
480960144019202560
KB123679179477
AVIF 345.6 KB
avifenc 1.4.1 −61%
50 60708090100
Score Quality
480960144019202560
KB10203672207
For the photo selected, each format’s quality setting (dashed) and the score it got (solid) at each width. The bars are the file sizes, on their own scale, with the sizes in KB below. The percentage under each total compares it with JPEG’s. Hover over or tap a width for its numbers.

AVIF is usually the smallest, though WebP sometimes wins at the narrowest width. Now and then, a WebP file even comes out larger than the JPEG at the same width. I keep it anyway, because the galleries offer AVIF first, so only browsers that can’t show AVIF use the WebP.

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.

Original
The edited photo
Colours
Extracted with colorthief-cli
Variants
JPEG, WebP, and AVIF from the pipeline, with hashed file names
Metadata
One YAML file per original
Original File nameSizeDimensionsHashPhoto ID
Variants File nameSizeDimensionsQualityScore
Colours Dominant colourPalette
Processing Tool versionsEncoder settings
Image storage
Cloudflare R2
Repository
GitHub
Site build
Hugo on Cloudflare Pages
Hugo looks up each photo ID for its file names, dimensions, and colour
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.

Original images are hashed, and a stable ID is derived from the hash, like birds/457514. Galleries refer to photos by that ID, so the galleries won’t break in case I need to reprocess an original and recreate the variants. The ID only changes if the original file does.

Cloudflare and browsers can cache the variants for a long time. Each file name includes a hash of the variant, 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, and dimensions) is stored in YAML files. On every push, Cloudflare Pages builds the site with Hugo, which reads the YAML to generate the gallery pages.

Which file the browser loads #

Each photo in a gallery is a <picture> element that lists its variants. This is the markup for one of them, with the file names shortened:

<picture>

  <!-- AVIF as preferred format -->
  <source type="image/avif"
          srcset="457514-480w.ecbae9d.avif   480w,
                  457514-960w.e2cb5ab.avif   960w,
                  457514-1440w.08ff78f.avif 1440w,
                  457514-1920w.8b56084.avif 1920w"
          sizes="(min-width: 1024px) 720px,
                 (min-width:  960px) 960px, 100vw">

  <!-- If AVIF isn't supported, the browser falls back to WebP -->
  <source type="image/webp"
          srcset="457514-480w.7a0a1ff.webp 480w, …"
          sizes="…">

  <!-- If WebP isn't supported, the browser falls back to JPEG -->
  <img src="457514-1920w.5f1d4a0.jpg"
       srcset="457514-480w.3e3dbcf.jpg 480w, …"
       sizes="…" alt="…">

</picture>

The browser reads it from the top and takes the first format it can show: AVIF in every current browser, WebP in some older ones, and JPEG in the rest. It never compares the sizes of the files, so the order is the fallback.

Then, from that format’s list, it picks the width that fits. sizes says how wide the photo will be on screen, and the browser multiplies that by the screen’s density, which is how many of its physical pixels fit across each pixel the page measures. A phone 390px wide with a screen density of 3 needs about 1,170 pixels across for the photo above, which fills the screen, so it fetches the 1440w file.

Screen density #

A page measures everything in CSS pixels, a unit that doesn’t depend on the screen. A screen draws them with its own physical pixels, and a sharper screen uses more of them for each CSS pixel, across and down. That number, counted across, is its density. It’s 1 on many monitors and older laptops, often 1.5 or 2 on today’s laptops, and 3 on many phones.

Density 1
16 pixels
Density 2
64 pixels
Density 3
144 pixels
The same 4 by 4 patch of a page, with the edge of a round shape running through it, drawn at screen densities of 1, 2, and 3. The higher the density, the smoother the edge. The outline marks one CSS pixel, drawn with 1, 4, and 9 physical pixels. Hover over or tap a pixel to move it.

For example, a photo shown 390 CSS pixels wide on a phone with a screen density of 3 covers 1,170 physical pixels across. To look sharp, the image needs at least as many pixels as the screen uses to draw it, so the browser fetches the 1440w file. A file with fewer pixels would be stretched to fit and look soft.

On the page #

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.