导语:本文将介绍一个完整的GIF(GraphicsInterChangeFormat)解码器,使用了LZW(Lempel-Ziv-Welch Encoding,串标压缩算法)解压缩器。
大家好,本文我将给大家介绍一个完整的GIF(GraphicsInterChangeFormat)解码器,使用了LZW(Lempel-Ziv-Welch Encoding,串标压缩算法)解压缩器。
GIF本身已有25年的历史,是最古老的图像压缩格式,至今仍在普遍使用。虽然它与流行的PNG和JPG格式有竞争,但它仍然是一种相当常见的图像压缩方法。正如你将看到的,GIF格式背后的许多设计考虑都是基于当时的硬件,而硬件本身现在已经过时了,但是格式总体上已经经受住了时间的考验。
在GIF文件的上下文中,图像是一个由彩色点组成的矩形数组,称为像素。由于CRT(Cathode-Ray Tube,阴极射线管)显示方式和它们的现代继承者——液晶显示器(LCD)的建造,这些像素实际上是三种不同颜色分量的组合:红色、绿色和蓝色。通过改变每个像素的颜色分量的强度,可以表示任何颜色。例如,深紫色是全强度红色和全强度蓝色的混合体。一般来说,颜色分量可以从0(不存在)到28=256(全亮度)不等。
早期具有彩色功能的图形硬件一次只能显示16种不同的颜色,但现代显示器可以显示红色、绿色和蓝色强度的任何组合。这可以计算出224=16777216种不同的颜色,远远超过人眼的实际识别能力。GIF可以追溯到20世纪80年代,当时16色显示器很常见,224“真彩色”显示器很少见,GIF基于调色板(palettes)的概念,设定其规范并称之为颜色表(color tables)。虽然16色显示器一次只能显示16种不同的颜色,但最前面的应用程序可以选择这16种颜色的224种可能的颜色分量强度组合,然后,GIF文件格式先描述这些颜色强度值的调色板,再将图像本身描述为该调色板中的一系列索引。

颜色表:

示例1:索引四色笑脸图像
示例1演示了一个粗略绘制的笑脸图像。因为它只有四种颜色,所以只需要四个调色板条目。这些调色板条目是从一个大的颜色空间中绘制的,但是这里的每个像素都可以用2位表示。
这种“调色板”的图像像素压缩得相当多。原则上每个像素需要3个字节来描述真彩色格式的图像,但是通过这种方法对图像进行调色板化,16色图像的大小可以立即缩小6倍,因为每个像素只需要4位。更清晰的颜色意味着更少的压缩,但是256色是相当多的,甚至一个256色调色板也代表了3:1的压缩比。
GIF允许更复杂的压缩,因为它允许编码器将图像分割成单独的块,每个块都可能有自己的调色板,例如在左上象限中最常出现的具有256种颜色的图像,可以将此象限指定为自己的块,具有和其他象限不同的单独的调色板。事实证明,没有人利用这种超压缩能力,而是改造它,以允许GIF动画。我稍后再谈这个。
GIF通过将LZW压缩算法应用于这些调色板索引,进一步压缩索引数据本身。它以一种相当粗糙的方式实现——索引本身被视为一个长的线性字节序列,LZW被应用到字节本身。这种方法没有考虑到这样一个事实,即,任何给定行的第一个像素与前一行的第一个像素,比上一行的最后一个像素更有可能与前一行的第一个像素相同(LZW算法就是这样看待像素的)。

示例2:100像素宽的GIF
在示例2中,像素1和101比像素100和101更有可能是相同的,但是LZW算法将看到像素101在100之后。尽管如此,LZW算法最终提供了相当好的压缩效果,它识别出单个行中的相似点,并重复从一行到下一行的模式。
与任何文件格式一样,GIF以标准化的头文件开头:

当然,ID标签是一个标准的3字节标签,是三个ASCII字节(G、I和F),它将文件标识为GIF文件。下面的3个字节是版本——定义了两个版本:87a和89a。你可能永远不会遇到87aGIF(是的,'87和'89指的是规范发布的年份)。宽度和高度紧随其后:它们以两个字节的形式给出,以小Endian格式,因此最大可能的GIF是216=65536 x65536像素,这仍然远远大于任何可用的计算机显示器的分辨率(但我一直保留着希望……)。
下一个字节是“字段”字节。字段字节被分解为(从最高有效位到最低有效位)如下:

W:标记全局颜色表的存在。回想一下,GIF允许编码器将图像细分为更大的压缩块,每个块都有自己的颜色表,或者,可以给出一个所有块都使用的单一“全局”颜色表,如果设置了这个位,则标题后面立即是一个全局颜色表。你会发现,几乎所有的GIF都包含一个全局颜色表。
X:颜色分辨率位数减1。这是显示单元被认为能够支持的颜色数的基数为2的对数——这与实际GIF中的颜色数不一样。如果显示器只能显示16种颜色,而GIF表示它期望显示器支持256种,那么软件很可能就会中止该显示器。现在,这个值是信息性的(充其量)。
Y:“排序”标志。为了理解排序标志的效用,假设一个只能够显示16种颜色的显示器显示了一个64色的GIF。GIF编码器可以使低分辨率显示器通过对调色板按颜色的频率排序来近似显示(可能完全跳过其他颜色或试图找到它们最接近的匹配)。如果编码器这样做,则设置此标志。如今,这面标志的设置并不是特别重要,因为16色显示器已经相当少了。
z:全局颜色表中的位数减1。因此,全局颜色表包含2z+1项。
背景颜色索引:如果没有指定由该GIF描述的矩形区域中的任何像素,则将其设置为颜色。你可能会问,如何将其不设置像素值?毕竟,GIF本身被描述为一个矩形。然而,回想一下,GIF允许图像被细分成更小的块,它们本身不一定占据整个图像显示区域。如果由于某种原因,左上和右下象限被定义,但是块的其余部分不是,则一些像素将被取消设置。
像素长宽比:同样,这也是信息性的(充其量),这告诉解码器在原始图像中像素宽度与高度的比值是多少。没有描述解码器如何利用这些信息,我不知道有哪个GIF解码器会对此给予任何关注。
然后,可以像以下清单1所示那样解析GIF标头:
typedef struct
{
unsigned short width;
unsigned short height;
unsigned char fields;
unsigned char background_color_index;
unsigned char pixel_aspect_ratio;
}
screen_descriptor_t;
/**
* @param gif_file the file descriptor of a file containing a
* GIF-encoded file. This should point to the first byte in
* the file when invoked.
*/
static void process_gif_stream( int gif_file )
{
unsigned char header[ 7 ];
screen_descriptor_t screen_descriptor;
int color_resolution_bits;
// A GIF file starts with a Header (section 17)
if ( read( gif_file, header, 6 ) != 6 )
{
perror( "Invalid GIF file (too short)" );
return;
}
header[ 6 ] = 0x0;
// XXX there's another format, GIF87a, that you may still find
// floating around.
if ( strcmp( "GIF89a", header ) )
{
fprintf( stderr,
"Invalid GIF file (header is '%s', should be 'GIF89a')\n",
header );
return;
}
// Followed by a logical screen descriptor
// Note that this works because GIFs specify little-endian order; on a
// big-endian machine, the height & width would need to be reversed.
// Can't use sizeof here since GCC does byte alignment;
// sizeof( screen_descriptor_t ) = 8!
if ( read( gif_file, &screen_descriptor, 7 ) < 7 )
{
perror( "Invalid GIF file (too short)" );
return;
}
color_resolution_bits = ( ( screen_descriptor.fields & 0x70 ) >> 4 ) + 1;
如果字段指示GIF包含一个全局颜色表,则它紧跟在标头之后。大小是由标志给出的,它指示全局颜色表包含了多少个3字节的条目,每个标记分别指示每个索引的红色、绿色和蓝色的强度。以下清单2演示了全局颜色表的解析:
typedef struct
{
unsigned char r;
unsigned char g;
unsigned char b;
}
rgb;
...
static void process_gif_stream( int gif_file )
{
unsigned char header[ 7 ];
screen_descriptor_t screen_descriptor;
int color_resolution_bits;
int global_color_table_size; // number of entries in global_color_table
rgb *global_color_table;
...
if ( screen_descriptor.fields & 0x80 )
{
int i;
// If bit 7 is set, the next block is a global color table; read it
global_color_table_size = 1 <<
( ( ( screen_descriptor.fields & 0x07 ) + 1 ) );
global_color_table = ( rgb * ) malloc( 3 * global_color_table_size );
// XXX this could conceivably return a short count...
if ( read( gif_file, global_color_table, 3 * global_color_table_size ) <
3 * global_color_table_size )
{
perror( "Unable to read global color table" );
return;
}
}
这就结束了GIF文件的标题部分。标题后面是一系列块,每个块用一个字节的块类型标识符标出。其中最重要的是图像描述符块0x2C,这是存储实际图像索引的地方。其次是挂载块0x3B,它指示一个GIF的结束——如果在文件结束之前没有遇到这个挂载块,则该文件以某种方式损坏。
因此,一旦解析了主标题和全局颜色表(如果有的话),接下来要做的就是开始查找块,并根据它们的类型解析它们,如下列清单3所示:
#define IMAGE_DESCRIPTOR 0x2C
#define TRAILER 0x3B
...
static void process_gif_stream( int gif_file )
{
unsigned char header[ 7 ];
screen_descriptor_t screen_descriptor;
int color_resolution_bits;
int global_color_table_size; // number of entries in global_color_table
rgb *global_color_table;
unsigned char block_type = 0x0;
...
while ( block_type != TRAILER )
{
if ( read( gif_file, &block_type, 1 ) < 1 )
{
perror( "Invalid GIF file (too short)" );
return;
}
switch ( block_type )
{
case IMAGE_DESCRIPTOR:
if ( !process_image_descriptor( gif_file,
global_color_table,
global_color_table_size,
color_resolution_bits ) )
{
return;
}
break;
case TRAILER:
break;
...
default:
fprintf( stderr, "Bailing on unrecognized block type %.02x\n",
block_type );
return;
}
}
}
图像描述符块本身以一个9字节的头结构开始:

左端,顶部,宽度、高度表明在整个图像的上下文中这个块的起点和终点。记住,GIF允许几个块组成一个完整的图像。
这些字段又被分成以下几个部分:

W:本地颜色表标志。
X:交错标志。
Y:排序标志。
Z:局部颜色表的大小。
第3项和第4项为“保留”且没有定义,它们应该始终设置为0。
本地颜色表、排序标志和本地颜色表的大小的解析与全局颜色表相同,本地颜色表的解析与全局颜色表的解析完全相同,这里不再重复。不管怎样,你会发现很少有.gif文件具有带有本地颜色表的图像描述符。
在全局标头定义的标志字节中没有类似项的一个位是隔行(interlace)标志。要记住,GIF是针对慢速显示硬件进行优化的,隔行扫描背后的理念是,显示器可以在解析过程的早期以粗糙的格式显示图像,并逐步显示越来越多的细节,直到图像完全处理完毕。因此,如果设置了隔行标志,则图像中的行将不按顺序排列:首先,每隔8行;接下来,从每8行的第4行开始;然后,从每4行的第2行开始;最后每隔一行,完成图像。

示例3:26行GIF的交错
示例3说明了如何存储交错文件。解释来说就是,绿色标记的行将被读取和显示,首先是黄色标记的行,然后是蓝色标记的行,最后是所有剩余的行。尽管如此,即使在今天,你还是会发现互联网上漂浮着一些交错的GIF文件。
忽略LCT的解析,解析图像描述符头,如下列清单4所示:
typedef struct
{
unsigned short image_left_position;
unsigned short image_top_position;
unsigned short image_width;
unsigned short image_height;
unsigned char fields;
}
image_descriptor_t;
...
static int process_image_descriptor( int gif_file,
rgb *gct,
int gct_size,
int resolution_bits )
{
image_descriptor_t image_descriptor;
int disposition;
// TODO there could actually be lots of these
if ( read( gif_file, &image_descriptor, 9 ) < 9 )
{
perror( "Invalid GIF file (too short)" );
disposition = 0;
goto done;
}
// TODO if LCT = true, read the LCT
...
disposition = 1;
done:
return disposition;
}
在图像描述符头之后,在逻辑上仍然包含在图像描述符块本身中,这是一系列的数据子块。这些数据子块是活动颜色表中的LZW压缩索引,如果图像描述符块包含一个局部颜色表,则这些是本地颜色表中的索引,否则,它们是全局颜色表中的索引。数据子块本身被进一步细分为255个字节的块,每个块声明其长度为它的第一个单字节。显然,由于单个GIF可以是655356×65536=4294967296像素(理论上来说),所以几乎所有的图像描述符都将由多个数据子块组成,即使它们是压缩的。然而,解码器目前没有足够的信息来判断有多少字节的压缩数据会跟随而来。因此,解码器必须转而继续读取数据子块,直到遇到一个零长度子块,表示数据的压缩结束。
这些压缩数据的子块可以读入内存,如以下清单5所示。在这里,我选择通过反复调用realloc来将整个混乱的东西塞进内存,任何值得认真对待的GIF实现都会在读取数据时对其进行解压缩,但这种实现更容易理解。
static int read_sub_blocks( int gif_file, unsigned char **data )
{
int data_length;
int index;
unsigned char block_size;
// Everything following are data sub-blocks, until a 0-sized block is
// encountered.
data_length = 0;
*data = NULL;
index = 0;
while ( 1 )
{
if ( read( gif_file, &block_size, 1 ) < 1 )
{
perror( "Invalid GIF file (too short): " );
return -1;
}
if ( block_size == 0 ) // end of sub-blocks
{
break;
}
data_length += block_size;
*data = realloc( *data, data_length );
// TODO this could be split across block size boundaries
if ( read( gif_file, *data + index, block_size ) <
block_size )
{
perror( "Invalid GIF file (too short): " );
return -1;
}
index += block_size;
}
return data_length;
}
static int process_image_descriptor( int gif_file,
rgb *gct,
int gct_size,
int resolution_bits )
{
int compressed_data_length;
unsigned char *compressed_data = NULL;
...
if ( read( gif_file, &image_descriptor, 9 ) < 9 )
{
perror( "Invalid GIF file (too short)" );
disposition = 0;
goto done;
}
compressed_data_length = read_sub_blocks( gif_file, &compressed_data );
...
done:
if ( compressed_data )
free( compressed_data );
return disposition;
}
此时,压缩数据完全包含在由COMPUT_DATA指定的缓冲区中,下一件要做的事就是解压缩它。但是,要使用压缩的GIF数据,需要做一些修改:
1.使用strcmp和strcat来实现LZW字典对GIF索引不起作用,因为它们包含嵌入零点,C的字符串操作将其解释为“字符串结尾”。
2.该实现假设压缩数据从8位代码开始,并在字典填充时扩展到9位。实际上,GIF允许可变的起始大小,一直到4位代码.。
要解决第一个问题,必须对字典本身进行改造。字典不是字符串数组,而是作为指针结构实现的。当遇到一个新的字典索引时,它是通过在最近的字典条目之上连接(使用strcat)最近读取的代码来创建的。更灵活的方法是定义一个结构,允许每个条目指向其前身,如下述清单6所示:
typedef struct
{
unsigned char byte;
int prev;
int len;
}
dictionary_entry_t;
现在,由5个0x0字节组成的字符串将在内存中表示为:

这些结构中的每一个都将由一个字典条目来指示,字典的索引(现在是指向DECUDY_ENTITY_t的指针数组)是从文件中读取的扩展代码。所以,如果前五个字节都是0(这很常见),并且全局颜色表包含64个条目:

在这里,长度声明只是一种便利,它不是绝对必要的(大多数GIF实现都省略了它,以加快解压缩速度)。如果在数据流中遇到代码69,解压缩器将查找字典[69],发现它的字节是0,发出0,然后跟踪反向指针&Dictory[68],发出另一个0,依此类推。但是,这些条目是以“向后”的方式构建的,因此有必要以相反的顺序发出它们。大多数GIF实现将字节推送到堆栈上,然后将其弹出,以执行实际的解压缩,与之相反的是,我会跟踪长度,这样我就知道在发出第一段代码时,输出缓冲区中要向前跳转多少字节。
一旦这个被平方,解决第二个问题——可变大小的LZW代码的问题——就很简单了:只需将起始代码大小传递到解压缩例程中即可。
清单7是完成的GIF友好解压缩例程。请注意,有一个12位代码的硬编码限制,一旦字典扩展到212=4096项,就不允许再增长了,由编码器来决定活动字典是否仍然在压缩方面做得很好,或者它是否应该发送一个清晰的代码,然后从头开始。
int uncompress( int code_length,
const unsigned char *input,
int input_length,
unsigned char *out )
{
int maxbits;
int i, bit;
int code, prev = -1;
dictionary_entry_t *dictionary;
int dictionary_ind;
unsigned int mask = 0x01;
int reset_code_length;
int clear_code; // This varies depending on code_length
int stop_code; // one more than clear code
int match_len;
clear_code = 1 << ( code_length );
stop_code = clear_code + 1;
// To handle clear codes
reset_code_length = code_length;
// Create a dictionary large enough to hold "code_length" entries.
// Once the dictionary overflows, code_length increases
dictionary = ( dictionary_entry_t * )
malloc( sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
// Initialize the first 2^code_len entries of the dictionary with their
// indices. The rest of the entries will be built up dynamically.
// Technically, it shouldn't be necessary to initialize the
// dictionary. The spec says that the encoder "should output a
// clear code as the first code in the image data stream". It doesn't
// say must, though...
for ( dictionary_ind = 0;
dictionary_ind < ( 1 << code_length );
dictionary_ind++ )
{
dictionary[ dictionary_ind ].byte = dictionary_ind;
// XXX this only works because prev is a 32-bit int (> 12 bits)
dictionary[ dictionary_ind ].prev = -1;
dictionary[ dictionary_ind ].len = 1;
}
// 2^code_len + 1 is the special "end" code; don't give it an entry here
dictionary_ind++;
dictionary_ind++;
// TODO verify that the very last byte is clear_code + 1
while ( input_length )
{
code = 0x0;
// Always read one more bit than the code length
for ( i = 0; i < ( code_length + 1 ); i++ )
{
// This is different than in the file read example; that
// was a call to "next_bit"
bit = ( *input & mask ) ? 1 : 0;
mask <<= 1;
if ( mask == 0x100 )
{
mask = 0x01;
input++;
input_length--;
}
code = code | ( bit << i );
}
if ( code == clear_code )
{
code_length = reset_code_length;
dictionary = ( dictionary_entry_t * ) realloc( dictionary,
sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
for ( dictionary_ind = 0;
dictionary_ind < ( 1 << code_length );
dictionary_ind++ )
{
dictionary[ dictionary_ind ].byte = dictionary_ind;
// XXX this only works because prev is a 32-bit int (> 12 bits)
dictionary[ dictionary_ind ].prev = -1;
dictionary[ dictionary_ind ].len = 1;
}
dictionary_ind++;
dictionary_ind++;
prev = -1;
continue;
}
else if ( code == stop_code )
{
if ( input_length > 1 )
{
fprintf( stderr, "Malformed GIF (early stop code)\n" );
exit( 0 );
}
break;
}
// Update the dictionary with this character plus the _entry_
// (character or string) that came before it
if ( ( prev > -1 ) && ( code_length < 12 ) )
{
if ( code > dictionary_ind )
{
fprintf( stderr, "code = %.02x, but dictionary_ind = %.02x\n",
code, dictionary_ind );
exit( 0 );
}
// Special handling for KwKwK
if ( code == dictionary_ind )
{
int ptr = prev;
while ( dictionary[ ptr ].prev != -1 )
{
ptr = dictionary[ ptr ].prev;
}
dictionary[ dictionary_ind ].byte = dictionary[ ptr ].byte;
}
else
{
int ptr = code;
while ( dictionary[ ptr ].prev != -1 )
{
ptr = dictionary[ ptr ].prev;
}
dictionary[ dictionary_ind ].byte = dictionary[ ptr ].byte;
}
dictionary[ dictionary_ind ].prev = prev;
dictionary[ dictionary_ind ].len = dictionary[ prev ].len + 1;
dictionary_ind++;
// GIF89a mandates that this stops at 12 bits
if ( ( dictionary_ind == ( 1 << ( code_length + 1 ) ) ) &&
( code_length < 11 ) )
{
code_length++;
dictionary = ( dictionary_entry_t * ) realloc( dictionary,
sizeof( dictionary_entry_t ) * ( 1 << ( code_length + 1 ) ) );
}
}
prev = code;
// Now copy the dictionary entry backwards into "out"
match_len = dictionary[ code ].len;
while ( code != -1 )
{
out[ dictionary[ code ].len - 1 ] = dictionary[ code ].byte;
if ( dictionary[ code ].prev == code )
{
fprintf( stderr, "Internal error; self-reference." );
exit( 0 );
}
code = dictionary[ code ].prev;
}
out += match_len;
}
}
我不想详细讨论这是如何工作的,但是等等,解压缩的调用方如何知道解压缩程序应该读取多少位?GIF实际上要求图像描述符的数据区域的第一个字节(在数据子块本身之前)是一个字节,指示第一个代码的长度。
unsigned char lzw_code_size;
...
if ( read( gif_file, &lzw_code_size, 1 ) < 1 )
{
perror( "Invalid GIF file (too short): " );
disposition = 0;
goto done;
}
compressed_data_length = read_sub_blocks( gif_file, &compressed_data );
通过定义解压缩,并且已知起始代码长度,图像描述符处理器现在可以对索引数据进行解压缩。
int uncompressed_data_length = 0; unsigned char *uncompressed_data = NULL; ... compressed_data_length = read_sub_blocks( gif_file, &compressed_data ); uncompressed_data_length = image_descriptor.image_width * image_descriptor.image_height; uncompressed_data = malloc( uncompressed_data_length ); uncompress( lzw_code_size, compressed_data, compressed_data_length, uncompressed_data ); disposition = 1; ... done: if ( compressed_data ) free( compressed_data ); if ( uncompressed_data ) free( uncompressed_data ); return disposition; }
就是这样,显示图像现在是一个索引的颜色表和反交错的数据行(如有必要的话)。所以,你可能会理所当然的想知道,为什么有一个以上的块类型定义时,图像描述符块类型包含整个图像。GIF'87标准认识到该规范可能需要再扩展,因此包含了一个特殊的块类型0x21以允许扩展。扩展块首先包括一个指示其描述的扩展类型的字节,下一个字节指示扩展的长度——通过将扩展的长度作为扩展的标准部分,不能识别扩展的解码器可以跳过扩展,但仍然会正确的处理文件。当然,扩展的剩余字节是特定于扩展的类型的。所有扩展后面都有数据子块,其格式与图像数据本身中的数据块完全相同——如果扩展没有任何关联数据,则后跟单个0字节的数据子块。
GIF'87没有定义任何扩展,但GIF'89编写了四个扩展:纯文本、注释、特定于应用程序和图形控件扩展。
· 注释扩展:这种扩展很少使用,它允许将可变长度的文本作为只读注释包含在GIF流中,这个注释不会显示在屏幕上,也没有明确说明用户如何能查看到它。
· 文本扩展:与注释扩展一样,该扩展允许在GIF中包含文本数据。但是,与注释扩展不同的是,此文本数据应该被覆盖在此图像的顶部,并作为其显示的一部分。编码器无法指定字体数据(事实上,这个扩展只允许固定宽度的字体,不允许可变宽度的字体),这也是非常罕见的。
· 特定于应用程序:此扩展允许将任意数据填充到GIF中,它由标识应用程序的8个字节和表示版本的3个字节组成。显然,子块中后面的数据依赖于应用程序ID。
· 最后也是最复杂的一个扩展类型是图形控制扩展(graphic control extension)。请记住,我提到没有人使用GIF的多块功能来对图像文件进行超压缩——相反,这用于创建动画图像文件。虽然GIF87a规范声明,当遇到多个图像块时,“图像之间没有暂停,每个图像都被处理器立即处理”,大多数GIF解码器用延迟覆盖图像以创造动画的幻觉。由于当时的软件开始时相当慢,我怀疑这种动画能力更像是意外,但它变得非常普遍,以至于现在有相当多的人相信GIF就是动画GIF。
问题是,没有标准的方法来表明这些动画的帧之间应该经过多长时间 。GIF89接受了这一点并将其与图形控件扩展编码。这种扩展很常见,不仅仅是动画GIF,而且你会一直遇到这些。图形控件扩展以字节字节开头:
r r x x x y z
r:保留,设置为0。
x:处理方法。这表示解码器在单独帧的显示之间应该做什么、是否应该空出显示区域。
y:用户输入标志。如果未设置,GIF动画应自动显示;否则,预期用户将在动画帧之间单击。
z:透明度,如果是真,那么扩展的最后一个字节是透明索引。
标志字节之后是帧之间的2字节延迟时间(以百分之一秒为单位)和单字节透明度索引,记住不能覆盖此索引,因为我们要使得底层框架可以“显示”。
要处理这些扩展类型,请添加新的块类型,如下述清单10所示:
#define EXTENSION_INTRODUCER 0x21
#define IMAGE_DESCRIPTOR 0x2C
...
static void process_gif_stream( int gif_file )
{
...
switch ( block_type )
{
case EXTENSION_INTRODUCER:
if ( !process_extension( gif_file ) )
{
return;
}
break;
case IMAGE_DESCRIPTOR:
然后处理扩展自身,如下述清单11所示:
#define EXTENSION_INTRODUCER 0x21
#define IMAGE_DESCRIPTOR 0x2C
#define TRAILER 0x3B
#define GRAPHIC_CONTROL 0xF9
#define APPLICATION_EXTENSION 0xFF
#define COMMENT_EXTENSION 0xFE
#define PLAINTEXT_EXTENSION 0x01
typedef struct
{
unsigned char extension_code;
unsigned char block_size;
}
extension_t;
typedef struct
{
unsigned char fields;
unsigned short delay_time;
unsigned char transparent_color_index;
}
graphic_control_extension_t;
typedef struct
{
unsigned char application_id[ 8 ];
unsigned char version[ 3 ];
}
application_extension_t;
typedef struct
{
unsigned short left;
unsigned short top;
unsigned short width;
unsigned short height;
unsigned char cell_width;
unsigned char cell_height;
unsigned char foreground_color;
unsigned char background_color;
}
plaintext_extension_t;
static int process_extension( int gif_file )
{
extension_t extension;
graphic_control_extension_t gce;
application_extension_t application;
plaintext_extension_t plaintext;
unsigned char *extension_data = NULL;
int extension_data_length;
if ( read( gif_file, &extension, 2 ) < 2 )
{
perror( "Invalid GIF file (too short): " );
return 0;
}
switch ( extension.extension_code )
{
case GRAPHIC_CONTROL:
if ( read( gif_file, &gce, 4 ) < 4 )
{
perror( "Invalid GIF file (too short): " );
return 0;
}
break;
case APPLICATION_EXTENSION:
if ( read( gif_file, &application, 11 ) < 11 )
{
perror( "Invalid GIF file (too short): " );
return 0;
}
break;
case 0xFE:
// comment extension; do nothing - all the data is in the
// sub-blocks that follow.
break;
case 0x01:
if ( read( gif_file, &plaintext, 12 ) < 12 )
{
perror( "Invalid GIF file (too short): " );
return 0;
}
break;
default:
fprintf( stderr, "Unrecognized extension code.\n" );
exit( 0 );
}
// All extensions are followed by data sub-blocks; even if it's
// just a single data sub-block of length 0
extension_data_length = read_sub_blocks( gif_file, &extension_data );
if ( extension_data != NULL )
free( extension_data );
return 1;
}
当然,在这种情况下,我所做的只是解析数据,我不是在解释它或用它做任何事情。请注意,在这种情况下,我正在硬编码每个扩展结构的长度——严格来说,这是不必要的,因为长度由扩展标头本身中的一个字节指示。我也终止了一个无法识别的扩展,违反了规范,其实我应该跳过它们的。下一步是将索引扩展为实际图像并显示它,同时遵守透明度和动画规范,我会把它留给真正的GIF解码器。到现在为止,你应该已经非常了解GIF图像格式的来龙去脉了。
参考文献:
1.特里韦尔奇“高性能数据压缩技术”,IEEE计算机,1984年6月。
2.GIF'89规范。
本文的源代码: