JPEG: your photos are secretly made of waves
Every photo you take, send or scroll past on the web
What problem does it solve?
How can a photo shrink to a tenth of its size and still look almost the same?
The big idea
JPEG cuts the image into 8×8 tiles and rewrites each tile as a mix of 64 checkerboard-like wave patterns, from smooth (one flat colour) to finely striped. That rewrite is the Discrete Cosine Transform, a close cousin of the Fourier transform that uses only cosines. Here's the aha: in a real photo almost all the energy sits in the few smooth patterns, and your eyes barely notice errors in the fine stripes. So JPEG rounds the fine-stripe amounts coarsely, often to zero, and the long runs of zeros compress beautifully.
How it works, step by step
- 1. Convert colour to brightness plus two colour channels, and usually store the colour at half resolution, since eyes are less sharp for colour.
- 2. Cut each channel into 8×8 blocks.
- 3. Apply the DCT: express each block as amounts of 64 cosine patterns.
- 4. Quantize: divide each amount by a number (bigger for fine patterns) and round. This is where detail is thrown away.
- 5. Read the amounts in a zigzag from smooth to fine, and pack the many zeros with run-length and Huffman coding.
The key formula
- the brightness of pixel n along a row of the block (N = 8)
- which wave pattern: 0 is flat, 7 is the finest stripes
- how much of pattern k the row contains
- the k-th cosine wave sampled at the 8 pixel centres; JPEG does this across rows and down columns
How fast is it?
Fast-Fourier-style tricks make the DCT cheap, and phones have hardware for it. Typical compression is around 10:1 with little visible loss. It's lossy: the rounding step can't be undone, and at high compression you see blocky 8×8 tiles and 'ringing' around sharp edges.
Try it yourself
- Save the same photo at JPEG quality 95, 50 and 10, and compare the file sizes and where the blockiness shows up first.
- Why does JPEG handle a photo of a sky well but a screenshot of text badly? (Sharp edges need lots of fine patterns.)
Fun fact
The DCT was invented by Nasir Ahmed, with T. Natarajan and K. R. Rao, in 1974, and Ahmed has said his grant proposal for it was originally rejected as too simple. JPEG became a standard in 1992, and the same cosine idea lives on inside video formats.