为什么 GIF 规范要求至少 2 位用于初始 LZW 代码大小?

Why does the GIF spec require at least 2-bits for the initial LZW code size?

我一直在努力弄清楚为什么 GIF89a 规范要求初始 LZW 代码大小至少为 2 位,即使在编码 1 位图像 (B&W) 时也是如此。在规范的附录 F 中,它表示如下:

ESTABLISH CODE SIZE

The first byte of the Compressed Data stream is a value indicating the minimum number of bits required to represent the set of actual pixel values. Normally this will be the same as the number of color bits. Because of some algorithmic constraints however, black & white images which have one color bit must be indicated as having a code size of 2.

我很好奇这些算法约束是什么。什么可能会阻止 GIF 中使用的 LZW 变体使用代码大小 1?这只是早期编码器或解码器的局限性吗?或者是否有一些奇怪的边缘情况可以通过正确的位组合表现出来?还是这里发生了完全不同的事情?

除了 01 的代码外,您还有一个 clear 代码和一个 end of information 代码。

引用自the spec

The output codes are of variable length, starting at +1 bits per code, up to 12 bits per code. This defines a maximum code value of 4095 (0xFFF). Whenever the LZW code value would exceed the current code length, the code length is increased by one.

如果您从代码大小 1 开始,则需要根据此规则立即增加代码大小。

此限​​制在实现中消除了一个 if(代码大小==1 时,第一个词汇短语代码的宽度==代码大小+2,在所有其他情况下宽度==代码大小+1)。
缺点是2色图片压缩比下降很小