JPEG - Idea and Practice/The decoding and drawing
The program that draws the picture from the file must do all the things that we have done in the opposite order. The width and the height of the picture and the quality factor(s) must be read from a header.
Let us sum up what must be done in the construction of the data part of the file:
- Divide up the picture in sxs-squares
- For each square:
- For each point, convert the RGB values to YCbCr values
- For the Y, Cb and Cr component, cosine transform the s2 numbers
- Order these 3 x s2 numbers after the zigzag principle
- Replace the first number of an s2-sequence (the DC term) by its derivation from the analogues number for the preceding square
- Quantize the 3 x s2 numbers
- In the resulting sequence of integers, replace each unbroken sequence of zeros by its length (possibly 0)
- Write each integer as a sequence of bits (having two parts: a code and a digit expression), so that the sequences can be joined together into a continuous stream of bits.
After the header (stating the width and the height and the quality factor) has been read, we must convert each read byte of the file to an 8-block of bits, and then decode the resulting stream of bits. Each sequence of bits determining an integer consists of two parts. The first part forms a code, which is designed so that we can see where it ends. We decode it, and in this way get a natural number m. The second part of the sequence is the next m bits in the stream, and these m bits are the binary digit expression of an integer. However, if this sequence begins with 0, this indicates that the integer is negative, and the 0 must be replaced by 1. Every second integer (being non-negative) states a number of zeros, and we (imagine that we) write down these zeros. We do this until we have numbers enough to draw an sxs-square of the picture, namely 3 x s2 numbers. These 3 x s2 numbers are obtained by cosine transform and by quantization of the s2 colour values for the three components. They must first be de-quantized by multiplying by the numbers we have divided by. After this the very first number of each s2-sequence (the DC term) must be added to the corresponding number for the preceding sxs-square, as these numbers represent differences. By the inverse zigzag procedure, each of the three s2-sequences is converted to a sxs-matrix of numbers g(u, v), u, v = 0, 1, ..., s-1, and to this matrix the inverse cosine transform is applied, giving a matrix f(i, j), i, j = 0, 1, ...,s-1, of colour values for the Y, Cb and Cr component. For each point (i, j) in the sxs-square, the three colour values f(i, j) make up an YCbCr triple, which is converted to a RGB triple, and the point in the picture corresponding to the point (i, j) in the square is coloured with these RGB values.