GIF LZW Minimum Code Size Byte Explained
The LZW minimum code size byte in a GIF file establishes the baseline bit width used to initialize the LZW decompressor for image data. Positioned immediately after the Image Descriptor (or Local Color Table, if present) and before the first raster data sub-block, this byte informs the decoder how many bits represent raw color indices, where control codes are positioned, and at what bit length the decoder must begin reading the compressed bitstream.
Defining Palette Depth and Base Literals
In GIF imaging, pixel data consists of indices that map to a color table. The LZW minimum code size (denoted as n) typically corresponds to the color depth (bits per pixel) of the image.
This value tells the decoder how many literal codes exist in the base alphabet:
- The decoder allocates \(2^n\) initial entries (from \(0\) to \(2^n - 1\)) for literal color values.
- Even if an image uses only 1 bit per pixel (2 colors), the GIF specification mandates a minimum code size of 2, ensuring that control codes have reserved positions distinct from pixel data.
Establishing Special Control Codes
The minimum code size byte directly determines the values for two critical LZW control codes:
- Clear Code (
CC): Calculated as \(2^n\). When encountered, it signals the decoder to reset its dictionary back to its initial state. - End of Information Code (
EOI): Calculated as \(2^n + 1\). This marks the termination of the raster data stream.
The first dynamic code created during compression is assigned the value \(2^n + 2\).
Setting the Initial Bit Reading Width
Variable-length code LZW compression starts reading symbols at a size larger than the raw index size to accommodate the control codes. The decoder uses the minimum code size to determine its starting read size:
\[\text{Initial Read Width} = n + 1 \text{ bits}\]
For example, if the minimum code size byte is 8 (standard for an 8-bit, 256-color image):
- Literal color indices occupy values
0through255. - The Clear Code is
256(\(2^8\)). - The EOI Code is
257(\(2^8 + 1\)). - The first available dictionary code is
258. - The decoder starts by reading codes with a width of 9 bits (\(8 + 1\)).
As the dictionary fills during decompression, this bit width increments automatically whenever the code count exceeds the capacity of the current bit length, up to a maximum limit of 12 bits.