14. JPEG: End to End
How DCT, quantization, and Huffman combine to compress photos
We've seen the Discrete Cosine Transform turn spatial data into frequency coefficients, and we've seen Huffman coding turn symbols into compact bitstreams. JPEG is the format that ties these together — along with a crucial middle step called quantization — into the most successful image compression standard ever created.
JPEG was finalized in 1992 by the Joint Photographic Experts Group and has remained the dominant photo format for over three decades. Every digital camera, every smartphone, every web browser speaks JPEG. Let's trace exactly what happens to an image, pixel by pixel, from input to compressed file.
The JPEG Pipeline
JPEG Compression Pipeline
┌──────────────────────────────────────────────┐
│ │
│ RGB Image │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ Color Convert │ RGB → YCbCr │
│ └───────┬────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ Chroma │ Downsample Cb, Cr │
│ │ Subsampling │ (4:2:0, 4:2:2, etc.) │
│ └───────┬────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ Block Split │ Divide into 8×8 blocks │
│ └───────┬────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ DCT │ Frequency transform │
│ └───────┬────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ Quantization │ Divide & round (LOSSY) │
│ └───────┬────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────┐ │
│ │ Entropy Coding │ Zigzag + RLE + Huffman │
│ └───────┬────────┘ │
│ │ │
│ ▼ │
│ Compressed JPEG file │
│ │
└──────────────────────────────────────────────┘
Every step is reversible except quantization — that's where information is permanently lost. Let's walk through each stage.
Step 1: Color Space Conversion
JPEG doesn't work directly on RGB. It first converts to YCbCr:
- Y (luma) — brightness, the part your eyes are most sensitive to
- Cb (blue-difference chroma) — how blue/yellow a pixel is
- Cr (red-difference chroma) — how red/cyan a pixel is
RGB to YCbCr conversion
Y = 0.299R + 0.587G + 0.114B
Cb = -0.169R - 0.331G + 0.500B + 128
Cr = 0.500R - 0.419G - 0.081B + 128
The coefficients aren't arbitrary — they reflect human vision. We perceive brightness (Y) with much higher resolution than color (Cb, Cr). This separation is what makes the next step possible.
Step 2: Chroma Subsampling
Since our eyes have poor color resolution, JPEG can downsample the chroma channels without visible degradation. The most common scheme is 4:2:0:
4:4:4 Full resolution for all channels (no subsampling)
4:2:2 Chroma at half horizontal resolution
4:2:0 Chroma at half horizontal AND half vertical resolution
With 4:2:0, the Cb and Cr channels are each one quarter the size of Y. For a 16×16 pixel region, Y has 256 samples but Cb and Cr have only 64 each. That's a 2:1 size reduction before any transform or coding — essentially "free" compression.
Exploiting human perception
This is the first of JPEG's two key insights: human vision has much lower spatial resolution for color than for brightness. We can throw away 75% of the color information and most people can't tell the difference. This is a fundamentally different trick from anything in lossless compression — it exploits the decoder (your brain), not patterns in the data.
Step 3: Block Splitting
Each channel (Y, Cb, Cr) is divided into 8×8 pixel blocks. If the image dimensions aren't multiples of 8, the edges are padded (typically by repeating the last row/column).
Why 8×8? It's a pragmatic compromise. Larger blocks would give the DCT more data to work with (better compression), but would also increase computational cost (DCT is O(n²) per block naively) and cause more visible artifacts when heavily compressed. 8×8 was the sweet spot in 1992, and it works well enough that nobody has changed it since.
Step 4: DCT (Discrete Cosine Transform)
Each 8×8 block of pixel values is transformed using the 2D DCT into an 8×8 block of frequency coefficients. We covered the DCT in detail in the previous article, so here's the quick summary:
- The top-left coefficient (DC) represents the block's average brightness
- Moving right increases horizontal frequency
- Moving down increases vertical frequency
- The bottom-right corner is the highest-frequency component
Before and after DCT
Pixel values (8×8): DCT coefficients (8×8):
┌────────────────────┐ ┌────────────────────────┐
│ 52 55 61 66 ... │ │ 415 -30 -61 27 ... │
│ 63 59 55 90 ... │ DCT │ -22 -62 -10 13 ... │
│ 62 59 68 113 ...│ ───► │ -11 21 14 -10 ... │
│ 63 58 71 122 ...│ │ -7 -14 5 3 ... │
│ ... │ │ ... │
└────────────────────┘ └────────────────────────┘
The DC coefficient (415) captures the average. The remaining AC coefficients capture increasingly fine detail. Natural images have most energy concentrated in the low frequencies — the high-frequency coefficients tend to be small.
Before applying the DCT, pixel values (0–255) are shifted by subtracting 128, centering them around zero. This improves the DCT's numerical behavior.
Step 5: Quantization — Where the Magic (and Loss) Happens
This is the critical step — the only irreversible step in the entire pipeline. Each DCT coefficient is divided by a corresponding value from a quantization table and rounded to the nearest integer:
The quantization table has a small divisor for low-frequency coefficients (preserve them accurately) and a large divisor for high-frequency coefficients (round them aggressively — often to zero).
Standard JPEG luminance quantization table (quality 50)
┌────────────────────────────────┐
│ 16 11 10 16 24 40 51 61 │
│ 12 12 14 19 26 58 60 55 │
│ 14 13 16 24 40 57 69 56 │
│ 14 17 22 29 51 87 80 62 │
│ 18 22 37 56 68 109 103 77 │
│ 24 35 55 64 81 104 113 92 │
│ 49 64 78 87 103 121 120 101 │
│ 72 92 95 98 112 100 103 99 │
└────────────────────────────────┘
Top-left values are small (16, 11, 10) — low frequencies are preserved. Bottom-right values are large (120, 101, 99) — high frequencies are crushed. A DCT coefficient of 30 divided by 99 and rounded gives 0 — that detail is gone forever.
Quality setting = quantization table scaling
When you save a JPEG at "quality 85" vs "quality 20," you're scaling this quantization table. Higher quality → smaller divisors → more coefficients survive → larger file. Lower quality → larger divisors → more coefficients become zero → smaller file. The table above is the baseline; quality 50.
After quantization, most 8×8 blocks look like this:
┌──────────────────────────────┐
│ 26 -3 -6 2 0 0 0 0 │
│ -2 -6 1 0 0 0 0 0 │
│ -1 2 1 0 0 0 0 0 │
│ -1 -1 0 0 0 0 0 0 │
│ 0 0 0 0 0 0 0 0 │
│ 0 0 0 0 0 0 0 0 │
│ 0 0 0 0 0 0 0 0 │
│ 0 0 0 0 0 0 0 0 │
└──────────────────────────────┘
A few non-zero values in the top-left corner, a sea of zeros everywhere else. That's exactly what we want — because the next step knows how to encode runs of zeros very efficiently.
Step 6: Zigzag Ordering
The 8×8 grid of quantized coefficients is read in a zigzag pattern that starts at the top-left and sweeps diagonally to the bottom-right:
This order groups low-frequency coefficients (the non-zero ones) at the start and pushes the long tail of zeros to the end. The result is a 1D sequence like:
26, -3, -2, -1, -6, -6, 2, 1, -1, 2, 1, -1, 0, 0, 1, 0, 0, 0, 0, 0, ... 0
All those trailing zeros can be encoded very efficiently.
Step 7: Entropy Coding
JPEG uses a two-part entropy coding scheme:
DC coefficients (the first value in each block)
DC values of adjacent blocks are usually similar (neighboring regions of an image have similar average brightness). So JPEG encodes the difference between consecutive DC values — delta coding, just like we'll cover in the next article.
Block 1 DC: 26
Block 2 DC: 23 → difference = -3
Block 3 DC: 25 → difference = 2
Each difference is encoded as a (category, extra bits) pair via Huffman coding. The category tells you the magnitude range, and the extra bits give the exact value within that range.
AC coefficients (the remaining 63 values)
AC coefficients are encoded using run-length coding combined with Huffman. Each non-zero AC value is preceded by a count of the zeros before it:
(run_of_zeros, value)
Encoding the zigzag sequence
Zigzag: 26, -3, -2, -1, -6, -6, 2, 1, -1, 2, 1, -1, 0, 0, 1, 0, 0, ... 0
DC: 26 (or delta from previous block)
AC pairs:
(0, -3) ← zero zeros before -3
(0, -2) ← zero zeros before -2
(0, -1) ← zero zeros before -1
(0, -6) ← zero zeros before -6
(0, -6)
(0, 2)
(0, 1)
(0, -1)
(0, 2)
(0, 1)
(0, -1)
(2, 1) ← TWO zeros before 1
(0,0) ← EOB (End Of Block) — all remaining are zero
Each (run, value) pair is Huffman-coded. The special symbol (0,0) means "everything from here to position 63 is zero" — for heavily quantized blocks, this often appears very early, making the block extremely compact.
The Complete Journey of One Block
Let's trace a single 8×8 block through the entire pipeline:
-
Original pixels (one channel, after color conversion)
64 values, each 0–255. Size: 64 bytes.
-
Level shift
Subtract 128 from each value. Now they range from -128 to 127. Same size, better DCT behavior.
-
2D DCT
64 pixel values become 64 frequency coefficients. Still 64 values — no compression yet, just a change of representation.
-
Quantization
Divide each coefficient by its quantization table entry and round. Most high-frequency coefficients become zero. Now we have maybe 10–15 non-zero values out of 64. This is where size drops — and where quality is lost.
-
Zigzag + RLE
Read in zigzag order, run-length encode the zeros. The 64 values become perhaps 12 (run, value) pairs plus an EOB marker.
-
Huffman coding
Encode each symbol with variable-length codes. Final output: maybe 30–50 bits for a block that started as 512 bits. That's 10:1 to 17:1 compression.
JPEG Artifacts — What Goes Wrong
When the quality setting is too low (quantization too aggressive), characteristic artifacts appear:
Blocking — The most recognizable JPEG artifact. Because each 8×8 block is quantized independently, neighboring blocks can end up with noticeably different average values, creating visible grid lines. At quality 10, almost every image shows blocking.
Ringing / Mosquito noise — Around sharp edges, quantization of high-frequency coefficients causes "ringing" — ghost echoes near the edge. This is the Gibbs phenomenon: the DCT basis functions are smooth cosines, and representing a sharp discontinuity requires many of them. When you zero out the high-frequency ones, the edge gets blurry and develops overshoot artifacts.
Color bleeding — Chroma subsampling reduces color resolution, so sharp color boundaries (like text on a colored background) get smeared. This is especially visible with 4:2:0 subsampling.
JPEG Variants
The JPEG standard actually defines several coding modes:
| Mode | Entropy Coder | Notes |
|---|---|---|
| Baseline | Huffman | The one everyone uses. 8-bit, sequential. |
| Progressive | Huffman | Encodes multiple passes — image loads blurry, then sharpens. Same final quality, slightly smaller file. |
| Arithmetic | Arithmetic coding | 5–10% smaller than Huffman, but was patent-encumbered until 2007. Some modern encoders support it. |
| Lossless | Huffman or arithmetic | Predictive coding, no DCT. Rarely used — PNG is better for lossless. |
Progressive JPEG is worth noting: instead of encoding block after block top-to-bottom, it encodes all DC coefficients first (a blurry preview), then progressively adds AC coefficients in multiple "scans." The image appears to materialize from blur to sharp. The total file size is often slightly smaller than baseline because the multiple passes allow better Huffman statistics.
Why JPEG Endures
JPEG is over 30 years old. Newer formats like JPEG 2000, WebP, AVIF, and JPEG XL all achieve better compression. Yet JPEG still dominates. Why?
- Universal support — every browser, every camera, every image editor, every operating system
- Hardware decoders — dedicated silicon in billions of devices
- Good enough — at quality 80–85, JPEG produces visually excellent results at reasonable file sizes
- Patent-free — baseline JPEG has no patent encumbrances (arithmetic mode did, but baseline Huffman never did)
- Simple — the entire pipeline can be implemented in a few hundred lines of code
The lesson of JPEG
JPEG isn't the best image codec. It hasn't been for years. But it was good enough, early enough, free enough, and simple enough to become universal. That combination is nearly impossible to displace. The same pattern repeats across computing: DEFLATE, TCP/IP, JSON, UTF-8 — adequate standards with network effects beat superior alternatives.
Try It Yourself — JPEG Pipeline Explorer
Adjust the quality slider and watch how quantization affects DCT coefficients. The left panel shows the original 8×8 block, the middle shows quantized coefficients (zeros highlighted), and the right shows the reconstructed block. Lower quality means more aggressive quantization — more zeros, smaller file, more artifacts.
DCT Coefficients (after quantization)
Statistics
Key Takeaways
- JPEG combines color conversion, chroma subsampling, DCT, quantization, and Huffman coding into a single pipeline
- Quantization is the only lossy step — it divides DCT coefficients by a quality-dependent table and rounds
- The quality setting scales the quantization table: higher quality → smaller divisors → more surviving coefficients → larger file
- Zigzag ordering groups non-zero low-frequency coefficients at the start, enabling efficient run-length coding of trailing zeros
- DC coefficients are delta-coded between blocks; AC coefficients use run-length + Huffman
- JPEG artifacts (blocking, ringing, color bleeding) are direct consequences of 8×8 block-independent quantization and chroma subsampling
- Despite being surpassed technically, JPEG's universality and simplicity make it nearly impossible to displace
JPEG uses delta coding for its DC coefficients — the difference between consecutive block averages. That's a small taste of a much more general technique. Delta and predictive coding can transform any signal with local correlation into something far more compressible.