An image block
A greyscale photo stores one brightness per pixel, from 0 (black) to 255 (white): one byte each. Here is one 8×8 block of a photo, 64 pixels, 64 bytes. JPEG codes an image block by block.
JPEG subtracts 128 from every pixel, so the values run from −128 to 127 and sit around zero. The top-left pixel 52 becomes −76. The block then goes to the DCT.
The DCT
The DCT (discrete cosine transform) treats a block as a mix of 64 fixed patterns. Pattern (u, v) is a cosine with u half-waves down and v across. (0, 0) is flat. Bigger u and v mean finer detail.
For each pattern, multiply it by the block pixel by pixel and add up: one number F(u, v). That gives 64 numbers. F(0, 0) = −415.375 is 8 × the average, −51.92. Nothing is lost yet: the DCT can be undone exactly.
Photos change slowly from pixel to pixel, so the low patterns do most of the work. F(0, 0) alone holds 86% of the energy (the sum of squares); the first 6 values in low-to-high order hold 90%. Fine-detail values are small.
Throwing detail away
Divide each F(u, v) by its entry in a table Q and round. Q is larger for fine detail, which the eye notices less. −415.375 / 16 rounds to −26. 44 of the 64 become 0. This is the step that loses information.
Read the 64 numbers in zigzag order, from low to high frequency. The non-zero values come first. After value number 26 (k = 25) every value is 0, so one end-of-block code replaces the last 38 zeros.
Each value becomes a code; common ones get short codes. With JPEG's standard tables this block takes 93 bits, padded to 12 bytes, instead of 64 bytes: about 5.3 times smaller. File headers add more, shared by every block.
Decoding and code
The decoder undoes each step: multiply q by Q, inverse DCT, add 128. The block comes back close, not exact: the mean error is 4.875 levels out of 255, the largest 15. Rounding threw that detail away.
In Python with numpy, the DCT is an 8×8 matrix C. F = C @ (g − 128) @ C.T gives all 64 values at once; np.round(F / Q) quantizes. F[0, 0] is −415.375 and q[0, 0] is −26, as in the figure.
The working
# step 1/10 · pixels one 8×8 block, 8-bit greyscale 0 = black ... 255 = white 64 pixels = 64 bytes = 512 bits row 0: 52 55 61 66 70 61 64 73 row 3: 63 58 71 122 154 106 70 69 an image is a 2-D signal: brightness as a function of (row, column)
The 8×8 block, its DCT, the quantized values and the decoded block are the worked example of the Wikipedia "JPEG" article; every number here is recomputed by this lesson's model. The coded bits were checked against a real encoder (libjpeg-turbo through Pillow at quality=50, which uses Table K.1 unchanged): the same 12 bytes. Q is Table K.1 of ITU-T T.81, which says its example tables "are based on psychovisual thresholding". Encoders scale it with a quality setting. The Huffman tables are T.81's example tables K.3 and K.5.