How GIF Encoders Initialize LZW Dictionaries

When compressing a GIF image, the encoder uses a modified version of the Lempel-Ziv-Welch (LZW) algorithm to replace repeating sequences of pixel data with shorter numerical codes. Before processing any pixel data, the encoder must properly initialize its string dictionary table to establish a shared baseline with the decoder. This article explains how the encoder defines the initial code size, populates the base color index entries, assigns special control codes, and prepares the dictionary to record new pixel sequences.

Establishing the Minimum Code Size

The initialization process begins by determining the "LZW Minimum Code Size." This value is derived directly from the image's color depth (the number of bits needed to represent the active palette). If an image uses an 8-bit palette (up to 256 colors), the minimum code size is 8. For palettes with very few colors (such as monochrome 1-bit images), GIF specifications mandate a minimum code size of at least 2, even if the color depth is 1.

Populating Base Color Indices

Once the minimum code size \(N\) is established, the encoder automatically reserves the first \(2^N\) entries in the dictionary table:

Adding Control Codes

Immediately following the individual color entries, the encoder assigns two mandatory control codes defined by the GIF standard:

  1. Clear Code (CC): Assigned the value \(2^N\). This code signals the decoder to wipe its dictionary and re-initialize it to the starting state when the table becomes full during compression.
  2. End of Information Code (EOI): Assigned the value \(2^N + 1\). This code signals that the compressed raster data stream for the current image block has concluded.

Defining the Next Available Code

With base colors and control codes in place, the encoder sets its next available dictionary entry pointer to \(2^N + 2\). Any new multi-pixel sequences encountered while scanning the raster data will be recorded starting from this index.

Setting Initial Bit Length

Finally, the encoder sets the initial bit width for outputting codes to \(N + 1\) bits. Because the control codes require an extra bit beyond the base palette size, the output bit length must immediately accommodate values up to at least \(2^N + 1\). The compression process then begins by emitting a mandatory Clear Code as the first symbol in the data stream, followed by the encoded pixel data.