GIF文件格式分析

来源:互联网 发布:输入数据生成图表 编辑:程序博客网 时间:2024/05/29 18:19

1、 什么是GIF

GIF作为网络上非常流行的图形文件格式,相应大家并不默生。GIF分为静态GIF动画GIF两种,扩展名为.gif,是一种压缩位图格式。GIF本质就是将多幅图像保存为一个图像文件,从而形成动画。更多的GIF描述参考百度百科或者维基百科。本文从网上各种摘录与拼接,旨在解析GIF文件格式。

2、GIF BNF状态图:


可见,一共包括:
 header,  logical screen descriptor,  global color tablegraphics control extensionimage descriptorlocal color table,  image data,  plain text extension,  application extension,  comment extension and trailer

header

GIF标识符和版本号

logical screen descriptor

显示描述

Global color table

紧跟着logical screen descriptor的全局颜色表

Graphics control extension

字符码21 F9打头的颜色控制扩展

Image Descriptor

字符码2C开头后跟8字节的图像描述

local color table

当前图像的颜色表

Image Data

LZW压缩后的图像数据

plain text extension

字符码21 01开头

application extension

字符码21 FF开头

comment extension

字符码21 FE开头

trailer

字符码3B结束符

 

3、             GIF二进制示例本人用一个GIF工具随意生成的一个GIF图像):

图片     

4、相应BNF状态描述:

1)  Header Block

图片分为两个3字节,分别为GIF图像标识与版本号“89a”。为什么是89a,自己查查吧。

2)  Local Screen Descriptor


图片
Canvase Width
Height:画布的宽与高。由于GIF采用小端编码,故Canvas WidthCanvas Height实则分别为00 0B00 1D

Packed Field(AA-1010 1010)

²  Glocal Color Table(1字节):是否有全局颜色表。

²  Color Resolution3字节):当Glocal Color Table1的时候有效,用于计算颜色的大小。此处忽略,见图像编码。

²  SortFlag1字节):目前已被忽略。

²  Size Of Global Color3字节):全局颜色表的大小。(此处为010,即为2。颜色表大小=2^(2+1)=8

3)  Global Color Table

全局颜色表,由Size Of Global Color计算得到全局颜色表有8项。由于一项记录包括RGB三个颜色值,帮Glocal Color Table Size = 8 * 3 = 24;

RGB索引

颜色值

0

00 00 01

1

8c 8c 8c

2

ff ff ff

3

dc dc dc

4

8d 8d 8d

5

00 00 00

6

00 00 00

7

00 00 00

 

4)  Graphics Control Extension


图片
字符码
21 F9开头,下一个字节为大小(不包括结尾符号,其实这里总是04),最后跟一个00结尾。

Packed Field(05):

²  Reserved For Furture Use(3字节):保留字段。

²  Disposal Method(3字节):和图片间显示切换相关。(A value of 2 would have meant that the canvas should be restored to the background color (as indicated by the logical screen descriptor). A value of 3 is defined to mean that the decoder should restore the canvas to its previous state before the current image was drawn. I don't believe that this value is widely supported but haven't had the chance to test it out. The behavior for values 4-7 are yet to be defined.

²  User Input Flag(1字节)flash是否等待用户输入。

²  Tansparent Color Flag1字节):是否透明。

Delay Time(32 00):切换到下一张图片的等待时间为0.32秒(1001秒)。

Transparent Color Index(05):透明背景的颜色,这里为5即黑色。

5)  Application Extension
 图片
图片 

6)  Image Descriptor

       图片

以字符码2C开头,后面紧跟10个字节。


图片Image Left
:本张图片在Canvas上的左坐标。

Image Top:本张图片在Canvas上的顶坐标。

Image Width:本张图片的宽。

Image Height:本张图片的高。

Local Color Table Flag:是否有自己的颜色索引表。

Interlace Flag:和切换展示有关。

SortFlag:目前被忽略。

Size of Local Color Table:当前索引表的大小。

7)  Image Data

3C为紧跟的字节数。数据其它字段的意义参见,数据的压缩。
图片
图片 

8)  Comment Extension


图片字符码
21 FE开头,然后紧跟大小描述,00结尾。主要用于增加一些图像描述。

9)  Plain Text Extension

字符码21 01开头,然后紧跟大小描述,00结尾。也是一些文本描述,此处不讨论。


图像数据见下一篇<LZW压缩算法>



原创粉丝点击