Principle · How it works

How transform coding compresses an image

Build an image block from simple patterns, round their weights, and compare the reconstructed picture with its original.

Start with the pictures we want to keep

JPEG compression can erase texture, expose block boundaries or create ripples beside edges. Follow one block to see where those changes come from. JPEG blocking, ringing and detail loss isolates those visible changes with a GPU quantisation experiment.

JPEG describes each 8×8 component block as a sum of predefined patterns. It stores rounded numbers saying how much of each pattern to add. The decoder adds the weighted patterns to rebuild sample values. Colour JPEG usually codes Y′, Cb and Cr separately; the patterns themselves are not coloured.

An RGB8 picture uses three bytes per pixel: about 6.22 MB for 1920×1080, before headers. Each 8-bit component stores a value from 0 to 255.

Two ways to spend fewer bits

Lossless compression uses repetition and structure to recover the input exactly. Not every input has enough structure to become smaller.

Lossy compression permits changes to the picture. Here, converting samples into pattern weights is reversible; rounding those weights loses information.

Chroma subsampling can remove colour detail before this stage. How digital images represent colour explains RGB, Y′CbCr and the 4:4:4, 4:2:2 and 4:2:0 grids.

Subtract a known starting level

Take an 8×8 block: 64 neighbouring samples of one component. Subtract 128 from each, shifting 0…255 to −128…127. Add it back after reconstruction.

Hats mark reconstructed values. This shift alone loses nothing and saves no bits.

Describe the block as patterns

The discrete cosine transform (DCT) expresses the block as weights of 64 cosine patterns. There are still 64 numbers. Each weight, or coefficient, sets how much of a pattern to add; it can be negative or larger than 255. Here u indexes horizontal variation and v vertical variation, from 0 to 7.

Constant · u=0, v=0
Across · u=1, v=0
Down · u=0, v=1
Fine · u=3, v=2
Four of the 64 patterns, with contrast enlarged to show their shapes. Light is positive; dark is negative.
1 · average only
4 patterns added
16 patterns added
64 · original block
Weighted patterns build the edge used below. All 64 recover it exactly here, before coefficient rounding.

Smooth areas often need mostly the constant pattern and a few slowly varying ones. Many other weights are small enough to round to zero.

Round the coefficients: this is the loss

Divide a coefficient c by a positive step Δ and round to an integer index q. Reconstruction multiplies q by Δ.

With Δ=16, both 21 and 23 become 1 and reconstruct as 16; 6 becomes zero. The original value within each rounding interval is lost. Larger steps can remove more patterns, changing the reconstructed samples.

One 8×8 block becomes 64 coefficient indices and a changed pictureThe left block shows the original edge. Subtracting 128, applying the DCT and rounding with a step of 32 produces the integer matrix in the middle. Multiplying those integers by 32, applying the inverse DCT and adding 128 produces the right block. All three panels are calculated with this fixed-step model. The JPEG experiment below uses an actual encoder with its own quantisation tables.Input blockQuantised indices-13-138-2-101-16-613-421-1-12-22-1-12-20-11-22-100-1100-12-22001-11-10001-11001-11-101-1000Reconstructed blockEncodeReconstructSubtract 128 → DCT → round(c / 32). Reconstruct with q × 32 → inverse DCT → add 128.Entropy coding would pack the indices into bits; it does not undo the rounding loss.
Scroll horizontally to inspect the full diagram. Keyboard: focus the diagram and use the arrow keys.

Here Δ=32 for every coefficient. JPEG instead uses a table of steps.

Pack the remaining symbols without losing more

In baseline sequential JPEG, the constant coefficient (DC) is stored as a difference from the preceding block’s DC in the same component. The other 63 (AC) follow a zigzag from low towards higher spatial frequencies.

Runs of zeros and an end-of-block symbol shorten the description. Huffman codes identify these symbols; extra bits carry the non-zero values. “Category” or “size” counts those extra value bits.

64 quantised coefficients, in zigzag order12 · 0 · 0 · −1 · 60 more zeros

The previous block’s DC is 10, so this block sends 12 − 10 = +2.

MeaningTable codeValue bitsBits
DC difference +2 · category 2011105
Two zeros, then −1 · run 2 / size 11110006
End of block · remaining 60 zeros1010—4

Scroll the table horizontally to see all bit fields.

Join the fields → 011101110001010 15 bits

Fixed-width storage: 64 × 5 = 320 bits. JPEG block payload: 15 bits.

These are real codes from JPEG’s example luminance tables. The decoder reads a table code, then the number of value bits it specifies. For category 1, 1 means +1 and 0 means −1.

Five signed bits (−16…15) suffice per coefficient in this example. The 15 bits count only the block payload. A complete JPEG also needs headers, shared tables and padding at the end of the scan. Packing preserves the rounded coefficients exactly; it adds no picture loss.

Compare image quality and compressed size

The quality slider spans 1–100% with extra travel at low qualities: 1–20% occupies about 44% of its length. Its readout gives the encoder quality, not the slider position.

Lower JPEG quality and watch the colour boundaries, gradients, feather detail and file size. Slanted edge and Ramp with fine texture isolate edge and texture changes. Both pictures always have the same pixel dimensions. The − and + buttons on either picture change both scales together. Fit shows the complete image; 100% maps each image pixel to one CSS pixel. Drag or scroll either view to inspect the same area. Clicking compares the selected 8×8 RGB fragments under both images and updates the luma-pattern breakdown below. Zoom magnifies the existing samples without adding detail.

JPEG compression

The image comparison needs JavaScript; the diagrams above show the static mechanism.

The original size counts raw RGB8 samples: width × height × 3 bytes. The JPEG size includes the complete file. Headers can make a tiny JPEG larger than its bitmap. Quality 100% still need not be lossless.

Predict inside the same picture

Video codecs can subtract a guess from reconstructed neighbours instead of a fixed 128. Nearby samples often leave a smaller difference to encode.

Copy the top edge down, then subtractDecoded top samples 40, 80, 120 and 160 repeat in every prediction row. Subtracting prediction from the current block gives rows of +2, 0, −2 and +4. Adding that difference back recovers every original sample.Already decoded · top neighbours4080120160Prediction4080120160408012016040801201604080120160Current block4282122162408012016038781181584484124164Difference+2+2+2+20000-2-2-2-2+4+4+4+4− prediction=Current − prediction = difference. Zero difference is middle grey.
Scroll horizontally to inspect the full diagram. Keyboard: focus the diagram and use the arrow keys.
H.264 4×4 luma, vertical mode. Repeat each top sample down its column. The current block differs by only a few code values in each row.

For the first sample, 42 − 40 = +2; adding 40 + 2 recovers 42. Exact differences make prediction reversible. Rounding their transform weights can introduce loss.

Other H.264 modes use left neighbours or averages. The mode tells the decoder how to form the same guess; unavailable neighbours at picture or slice boundaries limit the choices. This is intra prediction, within the current picture.

Video bitstreams also carry prediction modes, reference and motion information, and quantiser settings. The JPEG Huffman codes above do not apply to H.264’s syntax.

Where you have seen this mechanism

Where you may have seen transform coding
FormatFamiliar contextConnection to this experiment
JPEG (.jpg, .jpeg)Camera photographs and images saved from websites.8×8 DCT, quantisation tables and entropy coding.
Motion JPEG (MJPEG)Some camera recordings and JPEG video feeds.Each frame is a separate JPEG image.
MPEG-2 Video (H.262)DVD-Video and digital television recordings.8×8 DCT for picture data or motion-prediction residuals.
H.264/AVC and H.265/HEVCCompressed camera video, downloaded video and streams.Integer transforms, prediction and filtering; codec-specific block sizes.
Lossy WebPImages served by websites.VP8-based prediction and transforms; a separate lossless mode.
AVIF / AV1AVIF web images and AV1 video.AVIF stores AV1-coded images; several transform types and sizes.

MP4 and MOV are containers; check the codec inside. PNG uses lossless filtering and DEFLATE, rather than this DCT-rounding process. “JPEG” here means ordinary lossy DCT JPEG.

What this model leaves out

The static transform uses an orthonormal 8×8 DCT and uniform rounding, with half-step ties away from zero. A constant shifted block of 12 has DC weight 96 and all other weights zero. Values clip and round only for display.

The application uses the browser’s JPEG encoder, which chooses quantisation tables and chroma sampling. The colour test chart is encoded at its native 2048×2048 resolution, preserving the diagnostic patterns before JPEG encoding; procedural targets are 16×16. Fit only changes the displayed scale. The block view reads luma coefficients from that same file. Its floating-point inverse DCT can differ slightly from browser integer rounding. It supports baseline single-scan grey and Y′CbCr JPEG; other processes retain the full image comparison without the block view.

Continue with How video compression uses other frames to predict from other pictures.

References