An animated GIF of a rotating globe |
|
Filename extension |
|
---|---|
Internet media type |
|
Type code | GIFf |
Uniform Type Identifier (UTI) | com.compuserve.gif |
Magic number | GIF87a /GIF89a |
Developed by | CompuServe |
Initial release | 15 June 1987; 35 years ago[1] |
Latest release |
89a |
Type of format | lossless bitmap image format |
Website | www.w3.org/Graphics/GIF/spec-gif89a.txt |
The Graphics Interchange Format (GIF; GHIF or JIF, see pronunciation) is a bitmap image format that was developed by a team at the online services provider CompuServe led by American computer scientist Steve Wilhite and released on June 15, 1987.[1] It is in widespread usage on the World Wide Web due to its wide support and portability between applications and operating systems.
The format supports up to 8 bits per pixel for each image, allowing a single image to reference its own palette of up to 256 different colors chosen from the 24-bit RGB color space. It also supports animations and allows a separate palette of up to 256 colors for each frame. These palette limitations make GIF less suitable for reproducing color photographs and other images with color gradients but well-suited for simpler images such as graphics or logos with solid areas of color.
GIF images are compressed using the Lempel–Ziv–Welch (LZW) lossless data compression technique to reduce the file size without degrading the visual quality.
History[edit]
Further information: § Unisys and LZW patent enforcement
CompuServe introduced GIF on 15 June 1987 to provide a color image format for their file downloading areas. This replaced their earlier run-length encoding format, which was black and white only. GIF became popular because it used Lempel–Ziv–Welch data compression. Since this was more efficient than the run-length encoding used by PCX and MacPaint, fairly large images could be downloaded reasonably quickly even with slow modems.
The original version of GIF was called 87a.[1] This version already supported multiple images in a stream.
In 1989, CompuServe released an enhanced version, called 89a,[2] This version added:
- support for animation delays
- transparent background colors
- storage of application-specific metadata
- allowing text labels as text (not embedding them in the graphical data). As there is little control over display fonts, however, this feature is rarely used.
The two versions can be distinguished by looking at the first six bytes of the file (the «magic number» or signature), which, when interpreted as ASCII, read «GIF87a» or «GIF89a», respectively.
CompuServe encouraged the adoption of GIF by providing downloadable conversion utilities for many computers. By December 1987, for example, an Apple IIGS user could view pictures created on an Atari ST or Commodore 64.[3] GIF was one of the first two image formats commonly used on Web sites, the other being the black-and-white XBM.[4]
In September 1995 Netscape Navigator 2.0 added the ability for animated GIFs to loop.
While GIF was developed by CompuServe, it used the Lempel–Ziv–Welch (LZW) lossless data compression algorithm patented by Unisys in 1985. Controversy over the licensing agreement between Unisys and CompuServe in 1994 spurred the development of the Portable Network Graphics (PNG) standard. In 2004, all patents relating to the proprietary compression used for GIF expired.
The feature of storing multiple images in one file, accompanied by control data, is used extensively on the Web to produce simple animations.
The optional interlacing feature, which stores image scan lines out of order in such a fashion that even a partially downloaded image was somewhat recognizable, also helped GIF’s popularity,[5] as a user could abort the download if it was not what was required.
In May 2015 Facebook added support for GIF.[6][7] In January 2018 Instagram also added GIF stickers to the story mode.[8]
Terminology[edit]
As a noun, the word GIF is found in the newer editions of many dictionaries. In 2012, the American wing of the Oxford University Press recognized GIF as a verb as well, meaning «to create a GIF file», as in «GIFing was the perfect medium for sharing scenes from the Summer Olympics». The press’s lexicographers voted it their word of the year, saying that GIFs have evolved into «a tool with serious applications including research and journalism».[9][10]
Pronunciation[edit]
A humorous image announcing the launch of a Tumblr account for the White House suggests pronouncing GIF with a hard g.
The pronunciation of the first letter of GIF has been disputed since the 1990s. The most common pronunciations in English are (with a soft g as in gin) and (with a hard g as in gift), differing in the phoneme represented by the letter G. The creators of the format pronounced the acronym GIF as , with a soft g, with Wilhite stating that he intended for the pronunciation to deliberately echo the American peanut butter brand Jif, and CompuServe employees would often quip «choosy developers choose GIF», a spoof of Jif’s television commercials.[11] However, the word is widely pronounced as , with a hard g,[12] and polls have generally shown that this hard g pronunciation is more prevalent.[13][14]
Dictionary.com[15] cites both pronunciations, indicating as the primary pronunciation, while Cambridge Dictionary of American English[16] offers only the hard-g pronunciation. Merriam-Webster’s Collegiate Dictionary[17] and Oxford Dictionaries cite both pronunciations, but place the hard g first: .[18][19][20][21] The New Oxford American Dictionary gave only in its second edition[22] but updated it to in the third edition.[23]
The disagreement over the pronunciation has led to heated Internet debate. On the occasion of receiving a lifetime achievement award at the 2013 Webby Awards ceremony, Wilhite publicly rejected the hard-g pronunciation;[12][24][25] his speech led to more than 17,000 posts on Twitter and dozens of news articles.[26] The White House[12] and the TV program Jeopardy! also entered the debate in 2013.[25] In February 2020, The J.M. Smucker Company, the owners of the Jif brand, partnered with the animated image database and search engine Giphy to release a limited-edition «Jif vs. GIF» (hashtagged as #JIFvsGIF) jar of peanut butter that had a label humorously declaring the soft-g pronunciation to refer exclusively to the peanut butter, and GIF to be exclusively pronounced with the hard-g pronunciation.[27]
Usage[edit]
GIFs are suitable for sharp-edged line art with a limited number of colors, such as logos. This takes advantage of the format’s lossless compression, which favors flat areas of uniform color with well defined edges.[28] They can also be used to store low-color sprite data for games.[29] GIFs can be used for small animations and low-resolution video clips, or as reactions in online messaging used to convey emotion and feelings instead of using words. They are popular on social media platforms such as Tumblr,[30] Facebook and Twitter.[31]
File format[edit]
Conceptually, a GIF file describes a fixed-sized graphical area (the «logical screen») populated with zero or more «images». Many GIF files have a single image that fills the entire logical screen. Others divide the logical screen into separate sub-images. The images may also function as animation frames in an animated GIF file, but again these need not fill the entire logical screen.
GIF files start with a fixed-length header («GIF87a» or «GIF89a») giving the version, followed by a fixed-length Logical Screen Descriptor giving the pixel dimensions and other characteristics of the logical screen. The screen descriptor may also specify the presence and size of a Global Color Table (GCT), which follows next if present.
Thereafter, the file is divided into segments, each introduced by a 1-byte sentinel:
- An image (introduced by 0x2C, an ASCII comma
','
) - An extension block (introduced by 0x21, an ASCII exclamation point
'!'
) - The trailer (a single byte of value 0x3B, an ASCII semicolon
';'
), which should be the last byte of the file.
An image starts with a fixed-length Image Descriptor, which may specify the presence and size of a Local Color Table (which follows next if present). The image data follows: one byte giving the bit width of the unencoded symbols (which must be at least 2 bits wide, even for bi-color images), followed by a linked list of sub-blocks containing the LZW-encoded data.
Extension blocks (blocks that «extend» the 87a definition via a mechanism already defined in the 87a spec) consist of the sentinel, an additional byte specifying the type of extension, and a linked list of sub-blocks with the extension data. Extension blocks that modify an image (like the Graphic Control Extension that specifies the optional animation delay time and optional transparent background color) must immediately precede the segment with the image they refer to.
The linked lists used by the image data and the extension blocks consist of series of sub-blocks, each sub-block beginning with a byte giving the number of subsequent data bytes in the sub-block (1 to 255). The series of sub-blocks is terminated by an empty sub-block (a 0 byte).
This structure allows the file to be parsed even if not all parts are understood. A GIF marked 87a may contain extension blocks; the intent is that a decoder can read and display the file without the features covered in extensions it does not understand.
The full detail of the file format is covered in the GIF specification.[2]
Palettes[edit]
GIF is palette-based: the colors used in an image (a frame) in the file have their RGB values defined in a palette table that can hold up to 256 entries, and the data for the image refer to the colors by their indices (0–255) in the palette table. The color definitions in the palette can be drawn from a color space of millions of shades (224 shades, 8 bits for each primary), but the maximum number of colors a frame can use is 256. This limitation seemed reasonable when GIF was developed because few people could afford the hardware to display more colors simultaneously. Simple graphics, line drawings, cartoons, and grey-scale photographs typically need fewer than 256 colors.
Each frame can designate one index as a «transparent background color»: any pixel assigned this index takes on the color of the pixel in the same position from the background, which may have been determined by a previous frame of animation.
Many techniques, collectively called dithering, have been developed to approximate a wider range of colors with a small color palette by using pixels of two or more colors to approximate in-between colors. These techniques sacrifice spatial resolution to approximate deeper color resolution. While not part of the GIF specification, dithering can be used in images subsequently encoded as GIF images. This is often not an ideal solution for GIF images, both because the loss of spatial resolution typically makes an image look fuzzy on the screen, and because the dithering patterns often interfere with the compressibility of the image data, working against GIF’s main purpose.
In the early days of graphical web browsers[when?], graphics cards with 8-bit buffers (allowing only 256 colors) were common and it was fairly common to make GIF images using the websafe palette.[according to whom?] This ensured predictable display, but severely limited the choice of colors. When 24-bit color became the norm, palettes could instead be populated with the optimum colors for individual images.
A small color table may suffice for small images, and keeping the color table small allows the file to be downloaded faster. Both the 87a and 89a specifications allow color tables of 2n colors for any n from 1 through 8. Most graphics applications will read and display GIF images with any of these table sizes; but some do not support all sizes when creating images. Tables of 2, 16, and 256 colors are widely supported.
True color[edit]
Although GIF is almost never used for true color images, it is possible to do so.[32][33] A GIF image can include multiple image blocks, each of which can have its own 256-color palette, and the blocks can be tiled to create a complete image. Alternatively, the GIF89a specification introduced the idea of a «transparent» color where each image block can include its own palette of 255 visible colors plus one transparent color. A complete image can be created by layering image blocks with the visible portion of each layer showing through the transparent portions of the layers above.
An animated GIF illustrating a technique for displaying more than the typical limit of 256 colors
To render a full-color image as a GIF, the original image must be broken down into smaller regions having no more than 255 or 256 different colors. Each of these regions is then stored as a separate image block with its own local palette and when the image blocks are displayed together (either by tiling or by layering partially transparent image blocks), the complete, full-color image appears. For example, breaking an image into tiles of 16 by 16 pixels (256 pixels in total) ensures that no tile has more than the local palette limit of 256 colors, although larger tiles may be used and similar colors merged resulting in some loss of color information.[32]
Since each image block can have its own local color table, a GIF file having many image blocks can be very large, limiting the usefulness of full-color GIFs.[33] Additionally, not all GIF rendering programs handle tiled or layered images correctly. Many rendering programs interpret tiles or layers as animation frames and display them in sequence as an animation[32] with most web browsers automatically displaying the frames with a delay time of 0.1 seconds or more.[34][35][better source needed]
Example GIF file[edit]
Microsoft Paint saves a small black-and-white image as the following GIF file (illustrated enlarged). Paint does not make optimal use of GIF; due to the unnecessarily large color table (storing a full 256 colors instead of the used 2) and symbol width, this GIF file is not an efficient representation of the 15-pixel image. Although the Graphic Control Extension block declares color index 16 (hexadecimal 10) to be transparent, that index is not used in the image. The only color indexes appearing in the image data are decimal 40 and 255, which the Global Color Table maps to black and white, respectively. |
Sample image (enlarged), actual size 3 pixels wide by 5 high |
Note that the hex numbers in the following tables are in little-endian byte order, as the format specification prescribes.
Byte # (hex) | Hexadecimal | Text or value | Meaning | |||||||
---|---|---|---|---|---|---|---|---|---|---|
0 | 47 49 46 38 39 61 | GIF89a | Header | |||||||
6 | 03 00 | 3 | Logical screen width | |||||||
8 | 05 00 | 5 | Logical screen height | |||||||
A | F7 | GCT follows for 256 colors with resolution 3 × 8 bits/primary, the lowest 3 bits represent the bit depth minus 1, the highest true bit means that the GCT is present | ||||||||
B | 00 | 0 | Background color: index #0; #000000 black | |||||||
C | 00 | 0 | Default pixel aspect ratio, 0:0 | |||||||
D | 00 00 00 |
|
Global Color Table, color #0: #000000, black |
Bytes Dh to 30Ch in the example define a palette of 256 colors. |
||||||
10 | 80 00 00 |
|
Global Color Table, color #1: transparent bit, not used in image | |||||||
… | … | … | Global Color Table extends to 30A | |||||||
30A | FF FF FF |
|
Global Color Table, color #255: #ffffff, white | |||||||
30D | 21 F9 | Graphic Control Extension (comment fields precede this in most files) | ||||||||
30F | 04 | 4 | Amount of GCE data, 4 bytes | |||||||
310 | 01 | Transparent background color; this is a bit field, the lowest bit signifies transparency | ||||||||
311 | 00 00 | Delay for animation in hundredths of a second; not used | ||||||||
313 | 10 | 16 | Color number of transparent pixel in GCT | |||||||
314 | 00 | End of GCE block | ||||||||
315 | 2C | Image descriptor | ||||||||
316 | 00 00 00 00 | (0, 0) | North-west corner position of image in logical screen | |||||||
31A | 03 00 05 00 | (3, 5) | Image width and height in pixels | |||||||
31E | 00 | 0 | Local color table bit, 0 means none | |||||||
31F | 08 | 8 | Start of image, LZW minimum code size | |||||||
320 | 0B | 11 | Amount of LZW encoded image follow, 11 bytes | |||||||
321 | 00 51 FC 1B 28 70 A0 C1 83 01 01 | <image data> | 11 bytes of image data, see field 320 | |||||||
32C | 00 | 0 | End of image data block | |||||||
32D | 3B | File termination |
Image coding[edit]
The image pixel data, scanned horizontally from top left, are converted by LZW encoding to codes that are then mapped into bytes for storing in the file. The pixel codes typically don’t match the 8-bit size of the bytes, so the codes are packed into bytes by a «little-Endian» scheme: the least significant bit of the first code is stored in the least significant bit of the first byte, higher order bits of the code into higher order bits of the byte, spilling over into the low order bits of the next byte as necessary. Each subsequent code is stored starting at the least significant bit not already used.
This byte stream is stored in the file as a series of «sub-blocks». Each sub-block has a maximum length 255 bytes and is prefixed with a byte indicating the number of data bytes in the sub-block. The series of sub-blocks is terminated by an empty sub-block (a single 0 byte, indicating a sub-block with 0 data bytes).
For the sample image above the reversible mapping between 9-bit codes and bytes is shown below.
9-bit code | Byte | ||
---|---|---|---|
Hexadecimal | Binary | Binary | Hexadecimal |
100 | 1 00000000 | 00000000 | 00 |
028 | 00 0101000 | 0101000 1 | 51 |
0FF | 011 111111 | 111111 00 | FC |
103 | 1000 00011 | 00011 011 | 1B |
102 | 10000 0010 | 0010 1000 | 28 |
103 | 100000 011 | 011 10000 | 70 |
106 | 1000001 10 | 10 100000 | A0 |
107 | 10000011 1 | 1 1000001 | C1 |
10000011 | 83 | ||
101 | 1 00000001 | 00000001 | 01 |
0000000 1 | 01 |
A slight compression is evident: pixel colors defined initially by 15 bytes are exactly represented by 12 code bytes including control codes.
The encoding process that produces the 9-bit codes is shown below. A local string accumulates pixel color numbers from the palette, with no output action as long as the local string can be found in a code table. There is special treatment of the first two pixels that arrive before the table grows from its initial size by additions of strings. After each output code, the local string is initialized to the latest pixel color (that could not be included in the output code).
Table 9-bit string --> code code Action #0 | 000h Initialize root table of 9-bit codes palette | : colors | : #255 | 0FFh clr | 100h end | 101h | 100h Clear Pixel Local | color Palette string | BLACK #40 28 | 028h 1st pixel always to output WHITE #255 FF | String found in table 28 FF | 102h Always add 1st string to table FF | Initialize local string WHITE #255 FF FF | String not found in table | 0FFh - output code for previous string FF FF | 103h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table BLACK #40 FF FF 28 | String not found in table | 103h - output code for previous string FF FF 28 | 104h - add latest string to table 28 | - initialize local string WHITE #255 28 FF | String found in table WHITE #255 28 FF FF | String not found in table | 102h - output code for previous string 28 FF FF | 105h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table WHITE #255 FF FF FF | String not found in table | 103h - output code for previous string FF FF FF | 106h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table WHITE #255 FF FF FF | String found in table WHITE #255 FF FF FF FF | String not found in table | 106h - output code for previous string FF FF FF FF| 107h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table WHITE #255 FF FF FF | String found in table WHITE #255 FF FF FF FF | String found in table No more pixels 107h - output code for last string 101h End
For clarity the table is shown above as being built of strings of increasing length. That scheme can function but the table consumes an unpredictable amount of memory. Memory can be saved in practice by noting that each new string to be stored consists of a previously stored string augmented by one character. It is economical to store at each address only two words: an existing address and one character.
The LZW algorithm requires a search of the table for each pixel. A linear search through up to 4096 addresses would make the coding slow. In practice the codes can be stored in order of numerical value; this allows each search to be done by a SAR (Successive Approximation Register, as used in some ADCs), with only 12 magnitude comparisons. For this efficiency an extra table is needed to convert between codes and actual memory addresses; the extra table upkeeping is needed only when a new code is stored which happens at much less than pixel rate.
Image decoding[edit]
Decoding begins by mapping the stored bytes back to 9-bit codes. These are decoded to recover the pixel colors as shown below. A table identical to the one used in the encoder is built by adding strings by this rule:
Yes | add string for local code followed by first byte of string for incoming code |
No | add string for local code followed by copy of its own first byte |
shift 9-bit ----> Local Table Pixel code code code --> string Palette color Action 100h 000h | #0 Initialize root table of 9-bit codes : | palette : | colors 0FFh | #255 100h | clr 101h | end 028h | #40 BLACK Decode 1st pixel 0FFh 028h | Incoming code found in table | #255 WHITE - output string from table 102h | 28 FF - add to table 103h 0FFh | Incoming code not found in table 103h | FF FF - add to table | - output string from table | #255 WHITE | #255 WHITE 102h 103h | Incoming code found in table | - output string from table | #40 BLACK | #255 WHITE 104h | FF FF 28 - add to table 103h 102h | Incoming code found in table | - output string from table | #255 WHITE | #255 WHITE 105h | 28 FF FF - add to table 106h 103h | Incoming code not found in table 106h | FF FF FF - add to table | - output string from table | #255 WHITE | #255 WHITE | #255 WHITE 107h 106h | Incoming code not found in table 107h | FF FF FF FF - add to table | - output string from table | #255 WHITE | #255 WHITE | #255 WHITE | #255 WHITE 101h | End
LZW code lengths[edit]
Shorter code lengths can be used for palettes smaller than the 256 colors in the example. If the palette is only 64 colors (so color indexes are 6 bits wide), the symbols can range from 0 to 63, and the symbol width can be taken to be 6 bits, with codes starting at 7 bits. In fact, the symbol width need not match the palette size: as long as the values decoded are always less than the number of colors in the palette, the symbols can be any width from 2 to 8, and the palette size any power of 2 from 2 to 256. For example, if only the first four colors (values 0 to 3) of the palette are used, the symbols can be taken to be 2 bits wide with codes starting at 3 bits.
Conversely, the symbol width could be set at 8, even if only values 0 and 1 are used; these data would only require a two-color table. Although there would be no point in encoding the file that way, something similar typically happens for bi-color images: the minimum symbol width is 2, even if only values 0 and 1 are used.
The code table initially contains codes that are one bit longer than the symbol size in order to accommodate the two special codes clr and end and codes for strings that are added during the process. When the table is full the code length increases to give space for more strings, up to a maximum code 4095 = FFF(hex). As the decoder builds its table it tracks these increases in code length and it is able to unpack incoming bytes accordingly.
Uncompressed GIF[edit]
A 46×46 uncompressed GIF with 7-bit symbols (128 colors, 8-bit codes).
Click on the image for an explanation of the code.
The GIF encoding process can be modified to create a file without LZW compression that is still viewable as a GIF image. This technique was introduced originally as a way to avoid patent infringement. Uncompressed GIF can also be a useful intermediate format for a graphics programmer because individual pixels are accessible for reading or painting. An uncompressed GIF file can be converted to an ordinary GIF file simply by passing it through an image editor.
The modified encoding method ignores building the LZW table and emits only the root palette codes and the codes for CLEAR and STOP. This yields a simpler encoding (a 1-to-1 correspondence between code values and palette codes) but sacrifices all of the compression: each pixel in the image generates an output code indicating its color index. When processing an uncompressed GIF, a standard GIF decoder will not be prevented from writing strings to its dictionary table, but the code width must never increase since that triggers a different packing of bits to bytes.
If the symbol width is n, the codes of width n+1 fall naturally into two blocks: the lower block of 2n codes for coding single symbols, and the upper block of 2n codes that will be used by the decoder for sequences of length greater than one. Of that upper block, the first two codes are already taken: 2n for CLEAR and 2n + 1 for STOP. The decoder must also be prevented from using the last code in the upper block, 2n+1 − 1, because when the decoder fills that slot, it will increase the code width. Thus in the upper block there are 2n − 3 codes available to the decoder that won’t trigger an increase in code width. Because the decoder is always one step behind in maintaining the table, it does not generate a table entry upon receiving the first code from the encoder, but will generate one for each succeeding code. Thus the encoder can generate 2n − 2 codes without triggering an increase in code width. Therefore, the encoder must emit extra CLEAR codes at intervals of 2n − 2 codes or less to make the decoder reset the coding dictionary. The GIF standard allows such extra CLEAR codes to be inserted in the image data at any time. The composite data stream is partitioned into sub-blocks that each carry from 1 to 255 bytes.
For the sample 3×5 image above, the following 9-bit codes represent «clear» (100) followed by image pixels in scan order and «stop» (101).
100 028 0FF 0FF 0FF 028 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 101
After the above codes are mapped to bytes, the uncompressed file differs from the compressed file thus:
Byte # (hex) | Hexadecimal | Text or value | Meaning |
---|---|---|---|
320 | 14 | 20 | 20 bytes uncompressed image data follow |
321 | 00 51 FC FB F7 0F C5 BF 7F FF FE FD FB F7 EF DF BF 7F 01 01 | ||
335 | 00 | 0 | End of image data |
Compression example[edit]
The trivial example of a large image of solid color demonstrates the variable-length LZW compression used in GIF files.
Code | Pixels | Notes | |||
---|---|---|---|---|---|
No.Ni | ValueNi + 256 | Length(bits) | This codeNi | AccumulatedNi(Ni + 1)/2 | Relations using Ni only apply to same-color pixels until coding table is full. |
0 | 100h | 9 | Clear code table | ||
1 | FFh | 1 | 1 | Top left pixel color chosen as the highest index of a 256-color palette | |
2 | 102h | 2 | 3 | ||
3⋮255 | 103h⋮1FFh | 3⋮255 | 6⋮32640 | Last 9-bit code | |
256⋮767 | 200h⋮3FFh | 10 | 256⋮767 | 32896⋮294528 | Last 10-bit code |
768⋮1791 | 400h⋮7FFh | 11 | 768⋮1791 | 295296⋮1604736 | Last 11-bit code |
1792⋮3839 | 800h⋮FFFh | 12 | 1792⋮3839 | 1606528⋮7370880 | Code table full |
⋮ | FFFh | 3839 | The maximum code may repeat for more same-color pixels.Overall data compression asymptotically approaches 3839 × 8/12 = 2559+1/3 | ||
101h | End of image data |
The code values shown are packed into bytes which are then packed into blocks of up to 255 bytes. A block of image data begins with a byte that declares the number of bytes to follow. The last block of data for an image is marked by a zero block-length byte.
Interlacing[edit]
The GIF Specification allows each image within the logical screen of a GIF file to specify that it is interlaced; i.e., that the order of the raster lines in its data block is not sequential. This allows a partial display of the image that can be recognized before the full image is painted.
An interlaced image is divided from top to bottom into strips 8 pixels high, and the rows of the image are presented in the following order:
- Pass 1: Line 0 (the top-most line) from each strip.
- Pass 2: Line 4 from each strip.
- Pass 3: Lines 2 and 6 from each strip.
- Pass 4: Lines 1, 3, 5, and 7 from each strip.
The pixels within each line are not interlaced, but presented consecutively from left to right. As with non-interlaced images, there is no break between the data for one line and the data for the next. The indicator that an image is interlaced is a bit set in the corresponding Image Descriptor block.
Animated GIF[edit]
A GIF animation made of two photos, one morphing into the other
Although GIF was not designed as an animation medium, its ability to store multiple images in one file naturally suggested using the format to store the frames of an animation sequence. To facilitate displaying animations, the GIF89a spec added the Graphic Control Extension (GCE), which allows the images (frames) in the file to be painted with time delays, forming a video clip. Each frame in an animation GIF is introduced by its own GCE specifying the time delay to wait after the frame is drawn. Global information at the start of the file applies by default to all frames. The data is stream-oriented, so the file offset of the start of each GCE depends on the length of preceding data. Within each frame the LZW-coded image data is arranged in sub-blocks of up to 255 bytes; the size of each sub-block is declared by the byte that precedes it.
By default, an animation displays the sequence of frames only once, stopping when the last frame is displayed. To enable an animation to loop, Netscape in the 1990s used the Application Extension block (intended to allow vendors to add application-specific information to the GIF file) to implement the Netscape Application Block (NAB).[36] This block, placed immediately before the sequence of animation frames, specifies the number of times the sequence of frames should be played (1 to 65535 times) or that it should repeat continuously (zero indicates loop forever). Support for these repeating animations first appeared in Netscape Navigator version 2.0, and then spread to other browsers.[37] Most browsers now recognize and support NAB, though it is not strictly part of the GIF89a specification.
The following example shows the structure of the animation file Rotating earth (large).gif shown (as a thumbnail) in the article’s infobox.
Byte # (hex) | Hexadecimal | Text or value | Meaning |
---|---|---|---|
0 | 47 49 46 38 39 61 | GIF89a | Logical Screen Descriptor |
6 | 90 01 | 400 | Width in pixels |
8 | 90 01 | 400 | Height in pixels |
A | F7 | GCT follows for 256 colors with resolution 3 × 8 bits/primary | |
B | 00 | 0 | Background color: #000000, black |
C | 00 | 0 | Default pixel aspect ratio, 0:0 |
D | 00 | Global Color Table | |
⋮ | |||
30D | 21 FF | Application Extension | |
30F | 0B | 11 | Size of block including application name and verification bytes (always 11) |
310 | 4E 45 54 53 43 41 50 45 32 2E 30 | NETSCAPE2.0 | 8-byte application name plus 3 verification bytes |
31B | 03 | 3 | Number of bytes in the following sub-block |
31C | 01 | 1 | Index of the current data sub-block (always 1 for the NETSCAPE block) |
31D | FF FF | 65535 | Unsigned number of repetitions |
31F | 00 | End of the sub-block chain for the Application Extension block | |
320 | 21 F9 | Graphic Control Extension for frame #1 | |
322 | 04 | 4 | Number of bytes (4) in the current sub-block |
323 | 04 |
000..... ...001.. ......0. .......0 (broken into sections for easier reading) |
Reserved, 5 lower bits are bit field Disposal method 1: do not dispose No user input Transparent color, 0 means not given |
324 | 09 00 | 9 | Frame delay: 0.09 second delay before painting next frame |
326 | FF | Transparent color index (unused in this frame) | |
327 | 00 | End of sub-block chain for Graphic Control Extension block | |
328 | 2C | Image Descriptor of frame #1 | |
329 | 00 00 00 00 | (0, 0) | North-west corner position of image in logical screen: (0, 0) |
32D | 90 01 90 01 | (400, 400) | Frame width and height: 400 × 400 pixels |
331 | 00 | 0 | Local color table: 0 means none & no interlacing |
332 | 08 | 8 | Minimum LZW code size for Image Data of frame #1 |
333 | FF | 255 | Number of bytes of LZW image data in the following sub-block: 255 bytes |
334 | … | <image data> | Image data, 255 bytes |
433 | FF | 255 | Number of bytes of LZW image data in the following sub-block, 255 bytes |
434 | … | <image data> | Image data, 255 bytes |
⋮ | Repeat for next blocks | ||
92C0 | 00 | End of sub-block chain for this frame | |
92C1 | 21 F9 | Graphic Control Extension for frame #2 | |
⋮ | Repeat for next frames | ||
EDABD | 21 F9 | Graphic Control Extension for frame #44 | |
⋮ | Image information and data for frame #44 | ||
F48F5 | 3B | Trailer: Last byte in the file, signaling EOF |
The animation delay for each frame is specified in the GCE in hundredths of a second. Some economy of data is possible where a frame need only rewrite a portion of the pixels of the display, because the Image Descriptor can define a smaller rectangle to be rescanned instead of the whole image. Browsers or other displays that do not support animated GIFs typically show only the first frame.
The size and color quality of animated GIF files can vary significantly depending on the application used to create them. Strategies for minimizing file size include using a common global color table for all frames (rather than a complete local color table for each frame) and minimizing the number of pixels covered in successive frames (so that only the pixels that change from one frame to the next are included in the latter frame). More advanced techniques involve modifying color sequences to better match the existing LZW dictionary, a form of lossy compression. Simply packing a series of independent frame images into a composite animation tends to yield large file sizes. Tools are available to minimize the file size given an existing GIF.
Metadata[edit]
Metadata can be stored in GIF files as a comment block, a plain text block, or an application-specific application extension block. Several graphics editors use unofficial application extension blocks to include the data used to generate the image, so that it can be recovered for further editing.
All of these methods technically require the metadata to be broken into sub-blocks so that applications can navigate the metadata block without knowing its internal structure.
The Extensible Metadata Platform (XMP) metadata standard introduced an unofficial but now widespread «XMP Data» application extension block for including XMP data in GIF files.[38] Since the XMP data is encoded using UTF-8 without NUL characters, there are no 0 bytes in the data. Rather than break the data into formal sub-blocks, the extension block terminates with a «magic trailer» that routes any application treating the data as sub-blocks to a final 0 byte that terminates the sub-block chain.
Unisys and LZW patent enforcement[edit]
In 1977 and 1978, Jacob Ziv and Abraham Lempel published a pair of papers on a new class of lossless data-compression algorithms, now collectively referred to as LZ77 and LZ78. In 1983, Terry Welch developed a fast variant of LZ78 which was named Lempel–Ziv–Welch (LZW).[39][40]
Welch filed a patent application for the LZW method in June 1983. The resulting patent, US4558302,[41] granted in December 1985, was assigned to Sperry Corporation who subsequently merged with Burroughs Corporation in 1986 and formed Unisys.[39] Further patents were obtained in the United Kingdom, France, Germany, Italy, Japan and Canada.
In addition to the above patents, Welch’s 1983 patent also includes citations to several other patents that influenced it, including:
- two 1980 Japanese patents from NEC’s Jun Kanatsu,[42][43]
- U.S. Patent 4,021,782 (1974) from John S. Hoerning,
- U.S. Patent 4,366,551 (1977) from Klaus E. Holtz, and
- a 1981 German patent from Karl Eckhart Heinz.[44][45]
In June 1984, an article by Welch was published in the IEEE magazine which publicly described the LZW technique for the first time.[46] LZW became a popular data compression technique and, when the patent was granted, Unisys entered into licensing agreements with over a hundred companies.[39][47]
The popularity of LZW led CompuServe to choose it as the compression technique for their version of GIF, developed in 1987. At the time, CompuServe was not aware of the patent.[39] Unisys became aware that the version of GIF used the LZW compression technique and entered into licensing negotiations with CompuServe in January 1993. The subsequent agreement was announced on 24 December 1994.[40] Unisys stated that they expected all major commercial on-line information services companies employing the LZW patent to license the technology from Unisys at a reasonable rate, but that they would not require licensing, or fees to be paid, for non-commercial, non-profit GIF-based applications, including those for use on the on-line services.[47]
Following this announcement, there was widespread condemnation of CompuServe and Unisys, and many software developers threatened to stop using GIF. The PNG format (see below) was developed in 1995 as an intended replacement.[39][40][46] However, obtaining support from the makers of Web browsers and other software for the PNG format proved difficult and it was not possible to replace GIF, although PNG has gradually increased in popularity.[39] Therefore, GIF variations without LZW compression were developed. For instance the libungif library, based on Eric S. Raymond’s giflib, allows creation of GIFs that followed the data format but avoided the compression features, thus avoiding use of the Unisys LZW patent.[48] A 2001 Dr. Dobb’s article described a way to achieve LZW-compatible encoding without infringing on its patents.[49]
In August 1999, Unisys changed the details of their licensing practice, announcing the option for owners of certain non-commercial and private websites to obtain licenses on payment of a one-time license fee of $5000 or $7500.[50] Such licenses were not required for website owners or other GIF users who had used licensed software to generate GIFs. Nevertheless, Unisys was subjected to thousands of online attacks and abusive emails from users believing that they were going to be charged $5000 or sued for using GIFs on their websites.[51] Despite giving free licenses to hundreds of non-profit organizations, schools and governments, Unisys was completely unable to generate any good publicity and continued to be condemned by individuals and organizations such as the League for Programming Freedom who started the «Burn All GIFs» campaign in 1999.[52][53]
The United States LZW patent expired on 20 June 2003.[54] The counterpart patents in the United Kingdom, France, Germany and Italy expired on 18 June 2004, the Japanese patents expired on 20 June 2004, and the Canadian patent expired on 7 July 2004.[54] Consequently, while Unisys has further patents and patent applications relating to improvements to the LZW technique,[54] LZW itself (and consequently GIF) have been free to use since July 2004.[55]
Alternatives[edit]
PNG[edit]
Portable Network Graphics (PNG) was designed as a replacement for GIF in order to avoid infringement of Unisys’ patent on the LZW compression technique.[39] PNG offers better compression and more features than GIF,[56] animation being the only significant exception. PNG is more suitable than GIF in instances where true-color imaging and alpha transparency are required.
Although support for PNG format came slowly, new web browsers support PNG. Older versions of Internet Explorer do not support all features of PNG. Versions 6 and earlier do not support alpha channel transparency without using Microsoft-specific HTML extensions.[57] Gamma correction of PNG images was not supported before version 8, and the display of these images in earlier versions may have the wrong tint.[58]
For identical 8-bit (or lower) image data, PNG files are typically smaller than the equivalent GIFs, due to the more efficient compression techniques used in PNG encoding.[59] Complete support for GIF is complicated chiefly by the complex canvas structure it allows, though this is what enables the compact animation features.
Animation formats[edit]
Videos resolve many issues that GIFs present through common usage on the web. They include drastically smaller file sizes, the ability to surpass the 8-bit color restriction, and better frame-handling and compression through codecs. Virtually universal support for the GIF format in web browsers and a lack of official support for video in the HTML standard caused GIF to rise to prominence for the purpose of displaying short video-like files on the web.
- MNG («Multiple-image Network Graphics») was originally developed as a PNG-based solution for animations. MNG reached version 1.0 in 2001, but few applications support it.
- APNG («Animated Portable Network Graphics») was proposed by Mozilla in 2006. APNG is an extension to the PNG format as alternative to the MNG format. APNG is supported by most browsers as of 2019.[60] APNG provides the ability to animate PNG files, while retaining backwards compatibility in decoders that cannot understand the animation chunk (unlike MNG). Older decoders will simply render the first frame of the animation.
- The PNG group officially rejected APNG as an official extension on 20 April 2007.[61]
- There have been several subsequent proposals for a simple animated graphics format based on PNG using several different approaches.[62] Nevertheless, APNG is still under development by Mozilla and is supported in Firefox 3.0[63][64] while MNG support was dropped.[65][66] APNG is currently supported by all major web browsers including Chrome (since version 59.0), Opera, Firefox and Edge.
- Embedded Adobe Flash objects and
- MPEG files were used on some websites to display simple video, but required the use of an additional browser plugin.
- WebM and
- WebP are in development and are supported by some web browsers.[67]
- Other options for web animation include serving individual frames using AJAX, or
- animating SVG («Scalable vector graphics») images using JavaScript or SMIL («Synchronized Multimedia Integration Language»).[citation needed]
- With the introduction of widespread support of the HTML5 video (
<video>
) tag in most web browsers, some websites use a looped version of the video tag generated by JavaScript functions. This gives the appearance of a GIF, but with the size and speed advantages of compressed video.
- Notable examples are Gfycat and Imgur and their GIFV metaformat, which is really a video tag playing a looped MP4 or WebM compressed video.[68]
- HEIF («High Efficiency Image File Format») is an image file format, finalized in 2015, which uses a discrete cosine transform (DCT) lossy compression algorithm based on the HEVC video format, and related to the JPEG image format. In contrast to JPEG, HEIF supports animation.[69]
- Compared to the GIF format, which lacks DCT compression, HEIF allows significantly more efficient compression. HEIF stores more information and produces higher-quality animated images at a small fraction of an equivalent GIF’s size.[70]
- VP9 only supports alpha compositing with 4:2:0 chroma subsampling[71] in the YUVA420 pixel format, which may be unsuitable for GIFs that combine transparency with rasterised vector graphics with fine color details.
- AV1 video codec or AVIF can also be used either as a video or a sequenced image.
Uses[edit]
In April 2014, 4chan added support for silent WebM videos that are under 3 MB in size and 2 min in length,[72][73] and in October 2014, Imgur started converting any GIF files uploaded to the site to video and giving the link to the HTML player the appearance of an actual file with a .gifv
extension.[74][75]
In January 2016, Telegram started re-encoding all GIFs to MPEG-4 videos that «require up to 95% less disk space for the same image quality.»[76]
See also[edit]
- AVIF
- Cinemagraph, a partially animated photograph often in GIF
- Clear GIF, a technique used to check content access
- Comparison of graphics file formats
- GIF art, a form of digital art associated with GIF
- GIFBuilder, early animated GIF creation program
- GNU plotutils (supports pseudo-GIF, which uses run-length encoding rather than LZW)
- Microsoft GIF Animator, historic program to create simple animated GIFs
- Software patent
References[edit]
- ^ a b c «Graphics Interchange Format, Version 87a». W3C. 15 June 1987. Archived from the original on 22 December 2018. Retrieved 13 October 2012.
- ^ a b c «Graphics Interchange Format, Version 89a». W3C. 31 July 1990. Archived from the original on 22 December 2018. Retrieved 6 March 2009.
- ^ «Online Art». Compute!’s Apple Applications. December 1987. p. 10. Retrieved 14 September 2016.
- ^ Holdener III, Anthony (2008). Ajax: The Definitive Guide: Interactive Applications for the Web. O’Reilly Media. ISBN 978-0596528386.
- ^ Furht, Borko (2008). Encyclopedia of Multimedia. Springer. ISBN 978-0387747248.
- ^ McHugh, Molly (29 May 2015). «You Can Finally, Actually, Really, Truly Post GIFs on Facebook». Wired. wired.com. Archived from the original on 30 May 2015. Retrieved 29 May 2015.
- ^ Perez, Sarah (29 May 2015). «Facebook Confirms It Will Officially Support GIFs». techcrunch.com. Archived from the original on 30 May 2015. Retrieved 29 May 2015.
- ^ «Introducing GIF Stickers». Instagram. 23 January 2018. Archived from the original on 12 December 2019. Retrieved 19 September 2019.
- ^ «Oxford Dictionaries USA Word of the Year 2012». OxfordWords blog. Oxford American Dictionaries. 13 November 2012. Archived from the original on 3 August 2014. Retrieved 1 May 2013.
- ^ Flood, Alison (27 April 2013). «Gif is America’s word of the year? Now that’s what I call an omnishambles». Books blog. The Guardian. London. Archived from the original on 1 December 2016. Retrieved 1 May 2013.
- ^ Olsen, Steve. «The GIF Pronunciation Page». Archived from the original on 25 February 2009. Retrieved 6 March 2009.
- ^ a b c «Gif’s inventor says ignore dictionaries and say ‘Jif’«. BBC News. 22 May 2013. Archived from the original on 27 June 2018. Retrieved 22 May 2013.
- ^ Buck, Stephanie (21 October 2014). «70 percent of people worldwide pronounce GIF with a hard g«. Mashable. Archived from the original on 23 December 2021. Retrieved 24 December 2021.
- ^ van der Meulen, Marten (22 May 2019). «Obama, SCUBA or gift?: Authority and argumentation in online discussion on the pronunciation of GIF«. English Today. 36 (1): 45–50.
- ^ «GIF». The American Heritage Abbreviations Dictionary, Third Edition. Houghton Mifflin Company. 2005. Archived from the original on 3 September 2011. Retrieved 15 April 2007.
- ^ «GIF». The Cambridge Dictionary of American English. Cambridge University Press. Archived from the original on 27 February 2014. Retrieved 19 February 2014.
- ^ «Gif — Definition from the Merriam-Webster Dictionary». Merriam-Webster Dictionary. Merriam-Webster, Incorporated. Archived from the original on 22 October 2013. Retrieved 6 June 2013.
- ^ «GIF». Oxford Dictionaries Online. Oxford University Press. Archived from the original on 12 October 2014. Retrieved 7 October 2014.
- ^ «gif noun — Definition, pictures, pronunciation and usage notes | Oxford Advanced Learner’s Dictionary». Oxford Learner’s Dictionaries. Archived from the original on 24 November 2020. Retrieved 6 February 2021.
- ^ «GIF | Definition of GIF by Oxford Dictionary». Lexico. Archived from the original on 13 February 2021. Retrieved 6 February 2021.
- ^ Stevenson, Angus, ed. (2010). Oxford Dictionary of English (3rd ed.). Oxford University Press. ISBN 9780199571123. OCLC 729551189.
- ^ The New Oxford American Dictionary (2nd ed.). Oxford University Press. 2005. p. 711.
- ^ The New Oxford American Dictionary (3rd ed.). 2012. (part of the Macintosh built-in dictionaries).
- ^ O’Leary, Amy (21 May 2013). «An Honor for the Creator of the GIF». The New York Times. Archived from the original on 22 May 2013. Retrieved 22 May 2013.
- ^ a b Rothberg, Daniel (4 December 2013). «‘Jeopardy’ wades into ‘GIF’ pronunciation battle». Los Angeles Times. Archived from the original on 6 December 2013. Retrieved 4 December 2013.
- ^ O’Leary, Amy (23 May 2013). «Battle Over ‘GIF’ Pronunciation Erupts». The New York Times. Archived from the original on 16 December 2013. Retrieved 5 December 2013.
- ^ Valinsky, Jordan (February 25, 2020). «Jif settles the great debate with a GIF peanut butter jar». CNN. Archived from the original on February 25, 2020. Retrieved February 25, 2020.
- ^ Marur, D.R.; Bhaskar, V. (March 2012). «2012 International Conference on Devices, Circuits and Systems (ICDCS)». Devices, Circuits and Systems (ICDCS). International Conference on Devices, Circuits and Systems (ICDCS). Karunya University; Coimbatore, India: IEEE. pp. 297–301. doi:10.1109/ICDCSyst.2012.6188724. ISBN 9781457715457. Archived from the original on 2 July 2017. Retrieved 11 March 2015.
- ^ S. Chin; D. Iverson; O. Campesato; P. Trani (2011). Pro Android Flash (PDF). New York: Apress. p. 350. ISBN 9781430232315. Archived (PDF) from the original on 2 April 2015. Retrieved 11 March 2015.
- ^ Bakhshi, Saeideh; Shamma, David A.; Kennedy, Lyndon; Song, Yale; de Juan, Paloma; Kaye, Joseph «Jofish» (7 May 2016). «Fast, Cheap, and Good: Why Animated GIFs Engage Us». Proceedings of the 2016 CHI Conference on Human Factors in Computing Systems: 575–586. doi:10.1145/2858036.2858532. S2CID 7417853. Retrieved 17 August 2022.
- ^ Highfield, Tim; Leaver, Tama (2016). «Instagrammatics and digital methods: studying visual social media, from selfies and GIFs to memes and emoji». Communication Research and Practice. 2 (1): 47–62. doi:10.1080/22041451.2016.1155332. S2CID 148538216. Retrieved 17 August 2022.
- ^ a b c Andreas Kleinert (2007). «GIF 24 Bit (truecolor) extensions». Archived from the original on 16 March 2012. Retrieved 23 March 2012.
- ^ a b Philip Howard. «True-Color GIF Example». Archived from the original on 22 February 2015. Retrieved 23 March 2012.
- ^ «Nullsleep — Jeremiah Johnson — Animated GIF Minimum Frame Delay Browser Compatibility Study». Archived from the original on 10 October 2014. Retrieved 26 May 2015.
- ^ «They’re different! How to match the animation rate of gif files accross [sic] browsers». Developer’s Blog. 14 February 2012. Archived from the original on 1 February 2017. Retrieved 15 June 2017.
- ^ Royal Frazier. «All About GIF89a». Archived from the original on 18 April 1999. Retrieved 7 January 2013.
- ^
Scott Walter (1996). Web Scripting Secret Weapons. Que Publishing. ISBN 0-7897-0947-3. - ^ «XMP Specification Part 3: Storage in Files» (PDF). Adobe. 2016. pp. 11–12. Archived (PDF) from the original on 25 February 2018. Retrieved 16 August 2018.
- ^ a b c d e f g Greg Roelofs. «History of the Portable Network Graphics (PNG) Format». Archived from the original on 7 March 2012. Retrieved 23 March 2012.
- ^ a b c Stuart Caie. «Sad day… GIF patent dead at 20». Archived from the original on 10 February 2012. Retrieved 23 March 2012.
- ^ US 4558302, Welch, Terry A., published 1985-12-10, assigned to Sperry Corp.
- ^ JP patent S5719857A, Kanatsu, Jiyun, «Data compression storage device», published 1982-02-02, assigned to Nippon Electric Corp.
- ^ JP patent S57101937A, Kanatsu, Jiyun, «Data storage device», published 1986-20-24, assigned to Nippon Electric Corp.
- ^ DE patent 3118676, Eckhart, Heinz Karl, «Verfahren zur Kompression redundanter Folgen serieller Datenelemente [Method for compressing redundant sequences of serial data elements]», published 1982-12-02
- ^ U.S. Patent 4,558,302
- ^ a b «The GIF Controversy: A Software Developer’s Perspective». Archived from the original on 23 August 2016. Retrieved 26 May 2015.
- ^ a b «Unisys Clarifies Policy Regarding Patent Use in On-Line Service Offerings». Archived from the original on 7 February 2007. – archived by League for Programming Freedom
- ^ «Libungif». Archived from the original on 13 April 2015. Retrieved 26 May 2015.
- ^ Cargill, Tom (1 October 2001). «Replacing a Dictionary with a Square Root». Dr. Dobb’s Journal. Archived from the original on 28 June 2017. Retrieved 20 January 2017.
- ^ «LZW Software and Patent Information». Archived from the original on 8 June 2009. Retrieved 31 January 2007. – clarification of 2 September 1999
- ^ Unisys Not Suing (most) Webmasters for Using GIFs Archived 10 May 2017 at the Wayback Machine – Slashdot investigation into the controversy
- ^ «Burn All GIFs Day». Archived from the original on 13 October 1999.
- ^ Burn All GIFs Archived 3 February 2007 at the Wayback Machine – A project of the League for Programming Freedom (latest version)
- ^ a b c «License Information on GIF and Other LZW-based Technologies». Archived from the original on 2 June 2009. Retrieved 26 April 2005.
- ^ «Why There Are No GIF Files on GNU Web Pages». Free Software Foundation. Archived from the original on 19 May 2012. Retrieved 19 May 2012.
- ^ «PNG versus GIF Compression». 31 March 2007. Archived from the original on 15 July 2009. Retrieved 8 June 2009.
- ^ «AlphaImageLoader Filter». Microsoft. Archived from the original on 3 October 2014. Retrieved 26 May 2015.
- ^ «What’s New in Internet Explorer 7». MSDN. Archived from the original on 1 March 2009. Retrieved 6 March 2009.
- ^ «PNG Image File Format». Archived from the original on 14 June 2009. Retrieved 8 June 2009.
- ^ «Can I use… Support tables for HTML5, CSS3, etc». caniuse.com. Archived from the original on 19 February 2018. Retrieved 10 April 2020.
- ^ «VOTE FAILED: APNG 20070405a». SourceForge mailing list. 20 April 2007. Archived from the original on 13 February 2013. Retrieved 14 July 2013.
- ^ «Discussion for a simple «animated» PNG format». Archived from the original on 26 February 2009. Retrieved 12 July 2011.
- ^ «APNG Specification». Archived from the original on 5 July 2010. Retrieved 26 May 2015.
- ^ «Mozilla Labs » Blog Archive » Better animations in Firefox 3». Archived from the original on 7 March 2016. Retrieved 3 February 2016.
- ^ «195280 – Removal of MNG/JNG support». Archived from the original on 25 February 2021. Retrieved 26 May 2015.
- ^ «18574 – (mng) restore support for MNG animation format and JNG image format». Archived from the original on 17 March 2021. Retrieved 26 May 2015.
- ^ «Chromium Blog: Chrome 32 Beta: Animated WebP images and faster Chrome for Android touch input». Blog.chromium.org. 21 November 2013. Archived from the original on 17 July 2018. Retrieved 1 February 2014.
- ^ «Introducing GIFV — Imgur Blog». imgur.com. 9 October 2014. Archived from the original on 14 December 2014. Retrieved 14 December 2014.
- ^ Thomson, Gavin; Shah, Athar (2017). «Introducing HEIF and HEVC» (PDF). Apple Inc. Archived (PDF) from the original on 19 January 2020. Retrieved 5 August 2019.
- ^ «HEIF Comparison — High Efficiency Image File Format». Nokia Technologies. Archived from the original on 25 July 2019. Retrieved 5 August 2019.
- ^ «#3271 (Allow using additional pixel formats with libvpx-vp9) – FFmpeg». trac.ffmpeg.org. Archived from the original on 16 June 2020. Retrieved 10 April 2020.
- ^ Dewey, Caitlin. «Meet the technology that could make GIFs obsolete». The Washington Post. Archived from the original on 11 May 2015. Retrieved 4 February 2015.
- ^ «WebM support on 4chan». 4chan Blog. Archived from the original on 6 April 2014. Retrieved 4 February 2015.
- ^ «Introducing GIFV». Imgur. 9 August 2014. Archived from the original on 5 May 2020. Retrieved 21 July 2016.
- ^ Allan, Patrick (9 October 2014). «Imgur Revamps GIFs for Faster Speeds and Higher Quality with GIFV». Lifehacker. Archived from the original on 3 February 2015. Retrieved 4 February 2015.
- ^ «GIF Revolution». Official Telegram Blog. 4 January 2016. Archived from the original on 10 January 2016. Retrieved 4 January 2016.
External links[edit]
- The GIFLIB project
- spec-gif89a.txt GIF 89a specification on w3.org
- GIF 89a specification reformatted into HTML
- LZW and GIF explained
- Animated GIFs: a six-minute documentary produced by Off Book (web series)
- GifCities (The GeoCities Animated GIF Search Engine)
An animated GIF of a rotating globe |
|
Filename extension |
|
---|---|
Internet media type |
|
Type code | GIFf |
Uniform Type Identifier (UTI) | com.compuserve.gif |
Magic number | GIF87a /GIF89a |
Developed by | CompuServe |
Initial release | 15 June 1987; 35 years ago[1] |
Latest release |
89a |
Type of format | lossless bitmap image format |
Website | www.w3.org/Graphics/GIF/spec-gif89a.txt |
The Graphics Interchange Format (GIF; GHIF or JIF, see pronunciation) is a bitmap image format that was developed by a team at the online services provider CompuServe led by American computer scientist Steve Wilhite and released on June 15, 1987.[1] It is in widespread usage on the World Wide Web due to its wide support and portability between applications and operating systems.
The format supports up to 8 bits per pixel for each image, allowing a single image to reference its own palette of up to 256 different colors chosen from the 24-bit RGB color space. It also supports animations and allows a separate palette of up to 256 colors for each frame. These palette limitations make GIF less suitable for reproducing color photographs and other images with color gradients but well-suited for simpler images such as graphics or logos with solid areas of color.
GIF images are compressed using the Lempel–Ziv–Welch (LZW) lossless data compression technique to reduce the file size without degrading the visual quality.
History[edit]
Further information: § Unisys and LZW patent enforcement
CompuServe introduced GIF on 15 June 1987 to provide a color image format for their file downloading areas. This replaced their earlier run-length encoding format, which was black and white only. GIF became popular because it used Lempel–Ziv–Welch data compression. Since this was more efficient than the run-length encoding used by PCX and MacPaint, fairly large images could be downloaded reasonably quickly even with slow modems.
The original version of GIF was called 87a.[1] This version already supported multiple images in a stream.
In 1989, CompuServe released an enhanced version, called 89a,[2] This version added:
- support for animation delays
- transparent background colors
- storage of application-specific metadata
- allowing text labels as text (not embedding them in the graphical data). As there is little control over display fonts, however, this feature is rarely used.
The two versions can be distinguished by looking at the first six bytes of the file (the «magic number» or signature), which, when interpreted as ASCII, read «GIF87a» or «GIF89a», respectively.
CompuServe encouraged the adoption of GIF by providing downloadable conversion utilities for many computers. By December 1987, for example, an Apple IIGS user could view pictures created on an Atari ST or Commodore 64.[3] GIF was one of the first two image formats commonly used on Web sites, the other being the black-and-white XBM.[4]
In September 1995 Netscape Navigator 2.0 added the ability for animated GIFs to loop.
While GIF was developed by CompuServe, it used the Lempel–Ziv–Welch (LZW) lossless data compression algorithm patented by Unisys in 1985. Controversy over the licensing agreement between Unisys and CompuServe in 1994 spurred the development of the Portable Network Graphics (PNG) standard. In 2004, all patents relating to the proprietary compression used for GIF expired.
The feature of storing multiple images in one file, accompanied by control data, is used extensively on the Web to produce simple animations.
The optional interlacing feature, which stores image scan lines out of order in such a fashion that even a partially downloaded image was somewhat recognizable, also helped GIF’s popularity,[5] as a user could abort the download if it was not what was required.
In May 2015 Facebook added support for GIF.[6][7] In January 2018 Instagram also added GIF stickers to the story mode.[8]
Terminology[edit]
As a noun, the word GIF is found in the newer editions of many dictionaries. In 2012, the American wing of the Oxford University Press recognized GIF as a verb as well, meaning «to create a GIF file», as in «GIFing was the perfect medium for sharing scenes from the Summer Olympics». The press’s lexicographers voted it their word of the year, saying that GIFs have evolved into «a tool with serious applications including research and journalism».[9][10]
Pronunciation[edit]
A humorous image announcing the launch of a Tumblr account for the White House suggests pronouncing GIF with a hard g.
The pronunciation of the first letter of GIF has been disputed since the 1990s. The most common pronunciations in English are (with a soft g as in gin) and (with a hard g as in gift), differing in the phoneme represented by the letter G. The creators of the format pronounced the acronym GIF as , with a soft g, with Wilhite stating that he intended for the pronunciation to deliberately echo the American peanut butter brand Jif, and CompuServe employees would often quip «choosy developers choose GIF», a spoof of Jif’s television commercials.[11] However, the word is widely pronounced as , with a hard g,[12] and polls have generally shown that this hard g pronunciation is more prevalent.[13][14]
Dictionary.com[15] cites both pronunciations, indicating as the primary pronunciation, while Cambridge Dictionary of American English[16] offers only the hard-g pronunciation. Merriam-Webster’s Collegiate Dictionary[17] and Oxford Dictionaries cite both pronunciations, but place the hard g first: .[18][19][20][21] The New Oxford American Dictionary gave only in its second edition[22] but updated it to in the third edition.[23]
The disagreement over the pronunciation has led to heated Internet debate. On the occasion of receiving a lifetime achievement award at the 2013 Webby Awards ceremony, Wilhite publicly rejected the hard-g pronunciation;[12][24][25] his speech led to more than 17,000 posts on Twitter and dozens of news articles.[26] The White House[12] and the TV program Jeopardy! also entered the debate in 2013.[25] In February 2020, The J.M. Smucker Company, the owners of the Jif brand, partnered with the animated image database and search engine Giphy to release a limited-edition «Jif vs. GIF» (hashtagged as #JIFvsGIF) jar of peanut butter that had a label humorously declaring the soft-g pronunciation to refer exclusively to the peanut butter, and GIF to be exclusively pronounced with the hard-g pronunciation.[27]
Usage[edit]
GIFs are suitable for sharp-edged line art with a limited number of colors, such as logos. This takes advantage of the format’s lossless compression, which favors flat areas of uniform color with well defined edges.[28] They can also be used to store low-color sprite data for games.[29] GIFs can be used for small animations and low-resolution video clips, or as reactions in online messaging used to convey emotion and feelings instead of using words. They are popular on social media platforms such as Tumblr,[30] Facebook and Twitter.[31]
File format[edit]
Conceptually, a GIF file describes a fixed-sized graphical area (the «logical screen») populated with zero or more «images». Many GIF files have a single image that fills the entire logical screen. Others divide the logical screen into separate sub-images. The images may also function as animation frames in an animated GIF file, but again these need not fill the entire logical screen.
GIF files start with a fixed-length header («GIF87a» or «GIF89a») giving the version, followed by a fixed-length Logical Screen Descriptor giving the pixel dimensions and other characteristics of the logical screen. The screen descriptor may also specify the presence and size of a Global Color Table (GCT), which follows next if present.
Thereafter, the file is divided into segments, each introduced by a 1-byte sentinel:
- An image (introduced by 0x2C, an ASCII comma
','
) - An extension block (introduced by 0x21, an ASCII exclamation point
'!'
) - The trailer (a single byte of value 0x3B, an ASCII semicolon
';'
), which should be the last byte of the file.
An image starts with a fixed-length Image Descriptor, which may specify the presence and size of a Local Color Table (which follows next if present). The image data follows: one byte giving the bit width of the unencoded symbols (which must be at least 2 bits wide, even for bi-color images), followed by a linked list of sub-blocks containing the LZW-encoded data.
Extension blocks (blocks that «extend» the 87a definition via a mechanism already defined in the 87a spec) consist of the sentinel, an additional byte specifying the type of extension, and a linked list of sub-blocks with the extension data. Extension blocks that modify an image (like the Graphic Control Extension that specifies the optional animation delay time and optional transparent background color) must immediately precede the segment with the image they refer to.
The linked lists used by the image data and the extension blocks consist of series of sub-blocks, each sub-block beginning with a byte giving the number of subsequent data bytes in the sub-block (1 to 255). The series of sub-blocks is terminated by an empty sub-block (a 0 byte).
This structure allows the file to be parsed even if not all parts are understood. A GIF marked 87a may contain extension blocks; the intent is that a decoder can read and display the file without the features covered in extensions it does not understand.
The full detail of the file format is covered in the GIF specification.[2]
Palettes[edit]
GIF is palette-based: the colors used in an image (a frame) in the file have their RGB values defined in a palette table that can hold up to 256 entries, and the data for the image refer to the colors by their indices (0–255) in the palette table. The color definitions in the palette can be drawn from a color space of millions of shades (224 shades, 8 bits for each primary), but the maximum number of colors a frame can use is 256. This limitation seemed reasonable when GIF was developed because few people could afford the hardware to display more colors simultaneously. Simple graphics, line drawings, cartoons, and grey-scale photographs typically need fewer than 256 colors.
Each frame can designate one index as a «transparent background color»: any pixel assigned this index takes on the color of the pixel in the same position from the background, which may have been determined by a previous frame of animation.
Many techniques, collectively called dithering, have been developed to approximate a wider range of colors with a small color palette by using pixels of two or more colors to approximate in-between colors. These techniques sacrifice spatial resolution to approximate deeper color resolution. While not part of the GIF specification, dithering can be used in images subsequently encoded as GIF images. This is often not an ideal solution for GIF images, both because the loss of spatial resolution typically makes an image look fuzzy on the screen, and because the dithering patterns often interfere with the compressibility of the image data, working against GIF’s main purpose.
In the early days of graphical web browsers[when?], graphics cards with 8-bit buffers (allowing only 256 colors) were common and it was fairly common to make GIF images using the websafe palette.[according to whom?] This ensured predictable display, but severely limited the choice of colors. When 24-bit color became the norm, palettes could instead be populated with the optimum colors for individual images.
A small color table may suffice for small images, and keeping the color table small allows the file to be downloaded faster. Both the 87a and 89a specifications allow color tables of 2n colors for any n from 1 through 8. Most graphics applications will read and display GIF images with any of these table sizes; but some do not support all sizes when creating images. Tables of 2, 16, and 256 colors are widely supported.
True color[edit]
Although GIF is almost never used for true color images, it is possible to do so.[32][33] A GIF image can include multiple image blocks, each of which can have its own 256-color palette, and the blocks can be tiled to create a complete image. Alternatively, the GIF89a specification introduced the idea of a «transparent» color where each image block can include its own palette of 255 visible colors plus one transparent color. A complete image can be created by layering image blocks with the visible portion of each layer showing through the transparent portions of the layers above.
An animated GIF illustrating a technique for displaying more than the typical limit of 256 colors
To render a full-color image as a GIF, the original image must be broken down into smaller regions having no more than 255 or 256 different colors. Each of these regions is then stored as a separate image block with its own local palette and when the image blocks are displayed together (either by tiling or by layering partially transparent image blocks), the complete, full-color image appears. For example, breaking an image into tiles of 16 by 16 pixels (256 pixels in total) ensures that no tile has more than the local palette limit of 256 colors, although larger tiles may be used and similar colors merged resulting in some loss of color information.[32]
Since each image block can have its own local color table, a GIF file having many image blocks can be very large, limiting the usefulness of full-color GIFs.[33] Additionally, not all GIF rendering programs handle tiled or layered images correctly. Many rendering programs interpret tiles or layers as animation frames and display them in sequence as an animation[32] with most web browsers automatically displaying the frames with a delay time of 0.1 seconds or more.[34][35][better source needed]
Example GIF file[edit]
Microsoft Paint saves a small black-and-white image as the following GIF file (illustrated enlarged). Paint does not make optimal use of GIF; due to the unnecessarily large color table (storing a full 256 colors instead of the used 2) and symbol width, this GIF file is not an efficient representation of the 15-pixel image. Although the Graphic Control Extension block declares color index 16 (hexadecimal 10) to be transparent, that index is not used in the image. The only color indexes appearing in the image data are decimal 40 and 255, which the Global Color Table maps to black and white, respectively. |
Sample image (enlarged), actual size 3 pixels wide by 5 high |
Note that the hex numbers in the following tables are in little-endian byte order, as the format specification prescribes.
Byte # (hex) | Hexadecimal | Text or value | Meaning | |||||||
---|---|---|---|---|---|---|---|---|---|---|
0 | 47 49 46 38 39 61 | GIF89a | Header | |||||||
6 | 03 00 | 3 | Logical screen width | |||||||
8 | 05 00 | 5 | Logical screen height | |||||||
A | F7 | GCT follows for 256 colors with resolution 3 × 8 bits/primary, the lowest 3 bits represent the bit depth minus 1, the highest true bit means that the GCT is present | ||||||||
B | 00 | 0 | Background color: index #0; #000000 black | |||||||
C | 00 | 0 | Default pixel aspect ratio, 0:0 | |||||||
D | 00 00 00 |
|
Global Color Table, color #0: #000000, black |
Bytes Dh to 30Ch in the example define a palette of 256 colors. |
||||||
10 | 80 00 00 |
|
Global Color Table, color #1: transparent bit, not used in image | |||||||
… | … | … | Global Color Table extends to 30A | |||||||
30A | FF FF FF |
|
Global Color Table, color #255: #ffffff, white | |||||||
30D | 21 F9 | Graphic Control Extension (comment fields precede this in most files) | ||||||||
30F | 04 | 4 | Amount of GCE data, 4 bytes | |||||||
310 | 01 | Transparent background color; this is a bit field, the lowest bit signifies transparency | ||||||||
311 | 00 00 | Delay for animation in hundredths of a second; not used | ||||||||
313 | 10 | 16 | Color number of transparent pixel in GCT | |||||||
314 | 00 | End of GCE block | ||||||||
315 | 2C | Image descriptor | ||||||||
316 | 00 00 00 00 | (0, 0) | North-west corner position of image in logical screen | |||||||
31A | 03 00 05 00 | (3, 5) | Image width and height in pixels | |||||||
31E | 00 | 0 | Local color table bit, 0 means none | |||||||
31F | 08 | 8 | Start of image, LZW minimum code size | |||||||
320 | 0B | 11 | Amount of LZW encoded image follow, 11 bytes | |||||||
321 | 00 51 FC 1B 28 70 A0 C1 83 01 01 | <image data> | 11 bytes of image data, see field 320 | |||||||
32C | 00 | 0 | End of image data block | |||||||
32D | 3B | File termination |
Image coding[edit]
The image pixel data, scanned horizontally from top left, are converted by LZW encoding to codes that are then mapped into bytes for storing in the file. The pixel codes typically don’t match the 8-bit size of the bytes, so the codes are packed into bytes by a «little-Endian» scheme: the least significant bit of the first code is stored in the least significant bit of the first byte, higher order bits of the code into higher order bits of the byte, spilling over into the low order bits of the next byte as necessary. Each subsequent code is stored starting at the least significant bit not already used.
This byte stream is stored in the file as a series of «sub-blocks». Each sub-block has a maximum length 255 bytes and is prefixed with a byte indicating the number of data bytes in the sub-block. The series of sub-blocks is terminated by an empty sub-block (a single 0 byte, indicating a sub-block with 0 data bytes).
For the sample image above the reversible mapping between 9-bit codes and bytes is shown below.
9-bit code | Byte | ||
---|---|---|---|
Hexadecimal | Binary | Binary | Hexadecimal |
100 | 1 00000000 | 00000000 | 00 |
028 | 00 0101000 | 0101000 1 | 51 |
0FF | 011 111111 | 111111 00 | FC |
103 | 1000 00011 | 00011 011 | 1B |
102 | 10000 0010 | 0010 1000 | 28 |
103 | 100000 011 | 011 10000 | 70 |
106 | 1000001 10 | 10 100000 | A0 |
107 | 10000011 1 | 1 1000001 | C1 |
10000011 | 83 | ||
101 | 1 00000001 | 00000001 | 01 |
0000000 1 | 01 |
A slight compression is evident: pixel colors defined initially by 15 bytes are exactly represented by 12 code bytes including control codes.
The encoding process that produces the 9-bit codes is shown below. A local string accumulates pixel color numbers from the palette, with no output action as long as the local string can be found in a code table. There is special treatment of the first two pixels that arrive before the table grows from its initial size by additions of strings. After each output code, the local string is initialized to the latest pixel color (that could not be included in the output code).
Table 9-bit string --> code code Action #0 | 000h Initialize root table of 9-bit codes palette | : colors | : #255 | 0FFh clr | 100h end | 101h | 100h Clear Pixel Local | color Palette string | BLACK #40 28 | 028h 1st pixel always to output WHITE #255 FF | String found in table 28 FF | 102h Always add 1st string to table FF | Initialize local string WHITE #255 FF FF | String not found in table | 0FFh - output code for previous string FF FF | 103h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table BLACK #40 FF FF 28 | String not found in table | 103h - output code for previous string FF FF 28 | 104h - add latest string to table 28 | - initialize local string WHITE #255 28 FF | String found in table WHITE #255 28 FF FF | String not found in table | 102h - output code for previous string 28 FF FF | 105h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table WHITE #255 FF FF FF | String not found in table | 103h - output code for previous string FF FF FF | 106h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table WHITE #255 FF FF FF | String found in table WHITE #255 FF FF FF FF | String not found in table | 106h - output code for previous string FF FF FF FF| 107h - add latest string to table FF | - initialize local string WHITE #255 FF FF | String found in table WHITE #255 FF FF FF | String found in table WHITE #255 FF FF FF FF | String found in table No more pixels 107h - output code for last string 101h End
For clarity the table is shown above as being built of strings of increasing length. That scheme can function but the table consumes an unpredictable amount of memory. Memory can be saved in practice by noting that each new string to be stored consists of a previously stored string augmented by one character. It is economical to store at each address only two words: an existing address and one character.
The LZW algorithm requires a search of the table for each pixel. A linear search through up to 4096 addresses would make the coding slow. In practice the codes can be stored in order of numerical value; this allows each search to be done by a SAR (Successive Approximation Register, as used in some ADCs), with only 12 magnitude comparisons. For this efficiency an extra table is needed to convert between codes and actual memory addresses; the extra table upkeeping is needed only when a new code is stored which happens at much less than pixel rate.
Image decoding[edit]
Decoding begins by mapping the stored bytes back to 9-bit codes. These are decoded to recover the pixel colors as shown below. A table identical to the one used in the encoder is built by adding strings by this rule:
Yes | add string for local code followed by first byte of string for incoming code |
No | add string for local code followed by copy of its own first byte |
shift 9-bit ----> Local Table Pixel code code code --> string Palette color Action 100h 000h | #0 Initialize root table of 9-bit codes : | palette : | colors 0FFh | #255 100h | clr 101h | end 028h | #40 BLACK Decode 1st pixel 0FFh 028h | Incoming code found in table | #255 WHITE - output string from table 102h | 28 FF - add to table 103h 0FFh | Incoming code not found in table 103h | FF FF - add to table | - output string from table | #255 WHITE | #255 WHITE 102h 103h | Incoming code found in table | - output string from table | #40 BLACK | #255 WHITE 104h | FF FF 28 - add to table 103h 102h | Incoming code found in table | - output string from table | #255 WHITE | #255 WHITE 105h | 28 FF FF - add to table 106h 103h | Incoming code not found in table 106h | FF FF FF - add to table | - output string from table | #255 WHITE | #255 WHITE | #255 WHITE 107h 106h | Incoming code not found in table 107h | FF FF FF FF - add to table | - output string from table | #255 WHITE | #255 WHITE | #255 WHITE | #255 WHITE 101h | End
LZW code lengths[edit]
Shorter code lengths can be used for palettes smaller than the 256 colors in the example. If the palette is only 64 colors (so color indexes are 6 bits wide), the symbols can range from 0 to 63, and the symbol width can be taken to be 6 bits, with codes starting at 7 bits. In fact, the symbol width need not match the palette size: as long as the values decoded are always less than the number of colors in the palette, the symbols can be any width from 2 to 8, and the palette size any power of 2 from 2 to 256. For example, if only the first four colors (values 0 to 3) of the palette are used, the symbols can be taken to be 2 bits wide with codes starting at 3 bits.
Conversely, the symbol width could be set at 8, even if only values 0 and 1 are used; these data would only require a two-color table. Although there would be no point in encoding the file that way, something similar typically happens for bi-color images: the minimum symbol width is 2, even if only values 0 and 1 are used.
The code table initially contains codes that are one bit longer than the symbol size in order to accommodate the two special codes clr and end and codes for strings that are added during the process. When the table is full the code length increases to give space for more strings, up to a maximum code 4095 = FFF(hex). As the decoder builds its table it tracks these increases in code length and it is able to unpack incoming bytes accordingly.
Uncompressed GIF[edit]
A 46×46 uncompressed GIF with 7-bit symbols (128 colors, 8-bit codes).
Click on the image for an explanation of the code.
The GIF encoding process can be modified to create a file without LZW compression that is still viewable as a GIF image. This technique was introduced originally as a way to avoid patent infringement. Uncompressed GIF can also be a useful intermediate format for a graphics programmer because individual pixels are accessible for reading or painting. An uncompressed GIF file can be converted to an ordinary GIF file simply by passing it through an image editor.
The modified encoding method ignores building the LZW table and emits only the root palette codes and the codes for CLEAR and STOP. This yields a simpler encoding (a 1-to-1 correspondence between code values and palette codes) but sacrifices all of the compression: each pixel in the image generates an output code indicating its color index. When processing an uncompressed GIF, a standard GIF decoder will not be prevented from writing strings to its dictionary table, but the code width must never increase since that triggers a different packing of bits to bytes.
If the symbol width is n, the codes of width n+1 fall naturally into two blocks: the lower block of 2n codes for coding single symbols, and the upper block of 2n codes that will be used by the decoder for sequences of length greater than one. Of that upper block, the first two codes are already taken: 2n for CLEAR and 2n + 1 for STOP. The decoder must also be prevented from using the last code in the upper block, 2n+1 − 1, because when the decoder fills that slot, it will increase the code width. Thus in the upper block there are 2n − 3 codes available to the decoder that won’t trigger an increase in code width. Because the decoder is always one step behind in maintaining the table, it does not generate a table entry upon receiving the first code from the encoder, but will generate one for each succeeding code. Thus the encoder can generate 2n − 2 codes without triggering an increase in code width. Therefore, the encoder must emit extra CLEAR codes at intervals of 2n − 2 codes or less to make the decoder reset the coding dictionary. The GIF standard allows such extra CLEAR codes to be inserted in the image data at any time. The composite data stream is partitioned into sub-blocks that each carry from 1 to 255 bytes.
For the sample 3×5 image above, the following 9-bit codes represent «clear» (100) followed by image pixels in scan order and «stop» (101).
100 028 0FF 0FF 0FF 028 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 101
After the above codes are mapped to bytes, the uncompressed file differs from the compressed file thus:
Byte # (hex) | Hexadecimal | Text or value | Meaning |
---|---|---|---|
320 | 14 | 20 | 20 bytes uncompressed image data follow |
321 | 00 51 FC FB F7 0F C5 BF 7F FF FE FD FB F7 EF DF BF 7F 01 01 | ||
335 | 00 | 0 | End of image data |
Compression example[edit]
The trivial example of a large image of solid color demonstrates the variable-length LZW compression used in GIF files.
Code | Pixels | Notes | |||
---|---|---|---|---|---|
No.Ni | ValueNi + 256 | Length(bits) | This codeNi | AccumulatedNi(Ni + 1)/2 | Relations using Ni only apply to same-color pixels until coding table is full. |
0 | 100h | 9 | Clear code table | ||
1 | FFh | 1 | 1 | Top left pixel color chosen as the highest index of a 256-color palette | |
2 | 102h | 2 | 3 | ||
3⋮255 | 103h⋮1FFh | 3⋮255 | 6⋮32640 | Last 9-bit code | |
256⋮767 | 200h⋮3FFh | 10 | 256⋮767 | 32896⋮294528 | Last 10-bit code |
768⋮1791 | 400h⋮7FFh | 11 | 768⋮1791 | 295296⋮1604736 | Last 11-bit code |
1792⋮3839 | 800h⋮FFFh | 12 | 1792⋮3839 | 1606528⋮7370880 | Code table full |
⋮ | FFFh | 3839 | The maximum code may repeat for more same-color pixels.Overall data compression asymptotically approaches 3839 × 8/12 = 2559+1/3 | ||
101h | End of image data |
The code values shown are packed into bytes which are then packed into blocks of up to 255 bytes. A block of image data begins with a byte that declares the number of bytes to follow. The last block of data for an image is marked by a zero block-length byte.
Interlacing[edit]
The GIF Specification allows each image within the logical screen of a GIF file to specify that it is interlaced; i.e., that the order of the raster lines in its data block is not sequential. This allows a partial display of the image that can be recognized before the full image is painted.
An interlaced image is divided from top to bottom into strips 8 pixels high, and the rows of the image are presented in the following order:
- Pass 1: Line 0 (the top-most line) from each strip.
- Pass 2: Line 4 from each strip.
- Pass 3: Lines 2 and 6 from each strip.
- Pass 4: Lines 1, 3, 5, and 7 from each strip.
The pixels within each line are not interlaced, but presented consecutively from left to right. As with non-interlaced images, there is no break between the data for one line and the data for the next. The indicator that an image is interlaced is a bit set in the corresponding Image Descriptor block.
Animated GIF[edit]
A GIF animation made of two photos, one morphing into the other
Although GIF was not designed as an animation medium, its ability to store multiple images in one file naturally suggested using the format to store the frames of an animation sequence. To facilitate displaying animations, the GIF89a spec added the Graphic Control Extension (GCE), which allows the images (frames) in the file to be painted with time delays, forming a video clip. Each frame in an animation GIF is introduced by its own GCE specifying the time delay to wait after the frame is drawn. Global information at the start of the file applies by default to all frames. The data is stream-oriented, so the file offset of the start of each GCE depends on the length of preceding data. Within each frame the LZW-coded image data is arranged in sub-blocks of up to 255 bytes; the size of each sub-block is declared by the byte that precedes it.
By default, an animation displays the sequence of frames only once, stopping when the last frame is displayed. To enable an animation to loop, Netscape in the 1990s used the Application Extension block (intended to allow vendors to add application-specific information to the GIF file) to implement the Netscape Application Block (NAB).[36] This block, placed immediately before the sequence of animation frames, specifies the number of times the sequence of frames should be played (1 to 65535 times) or that it should repeat continuously (zero indicates loop forever). Support for these repeating animations first appeared in Netscape Navigator version 2.0, and then spread to other browsers.[37] Most browsers now recognize and support NAB, though it is not strictly part of the GIF89a specification.
The following example shows the structure of the animation file Rotating earth (large).gif shown (as a thumbnail) in the article’s infobox.
Byte # (hex) | Hexadecimal | Text or value | Meaning |
---|---|---|---|
0 | 47 49 46 38 39 61 | GIF89a | Logical Screen Descriptor |
6 | 90 01 | 400 | Width in pixels |
8 | 90 01 | 400 | Height in pixels |
A | F7 | GCT follows for 256 colors with resolution 3 × 8 bits/primary | |
B | 00 | 0 | Background color: #000000, black |
C | 00 | 0 | Default pixel aspect ratio, 0:0 |
D | 00 | Global Color Table | |
⋮ | |||
30D | 21 FF | Application Extension | |
30F | 0B | 11 | Size of block including application name and verification bytes (always 11) |
310 | 4E 45 54 53 43 41 50 45 32 2E 30 | NETSCAPE2.0 | 8-byte application name plus 3 verification bytes |
31B | 03 | 3 | Number of bytes in the following sub-block |
31C | 01 | 1 | Index of the current data sub-block (always 1 for the NETSCAPE block) |
31D | FF FF | 65535 | Unsigned number of repetitions |
31F | 00 | End of the sub-block chain for the Application Extension block | |
320 | 21 F9 | Graphic Control Extension for frame #1 | |
322 | 04 | 4 | Number of bytes (4) in the current sub-block |
323 | 04 |
000..... ...001.. ......0. .......0 (broken into sections for easier reading) |
Reserved, 5 lower bits are bit field Disposal method 1: do not dispose No user input Transparent color, 0 means not given |
324 | 09 00 | 9 | Frame delay: 0.09 second delay before painting next frame |
326 | FF | Transparent color index (unused in this frame) | |
327 | 00 | End of sub-block chain for Graphic Control Extension block | |
328 | 2C | Image Descriptor of frame #1 | |
329 | 00 00 00 00 | (0, 0) | North-west corner position of image in logical screen: (0, 0) |
32D | 90 01 90 01 | (400, 400) | Frame width and height: 400 × 400 pixels |
331 | 00 | 0 | Local color table: 0 means none & no interlacing |
332 | 08 | 8 | Minimum LZW code size for Image Data of frame #1 |
333 | FF | 255 | Number of bytes of LZW image data in the following sub-block: 255 bytes |
334 | … | <image data> | Image data, 255 bytes |
433 | FF | 255 | Number of bytes of LZW image data in the following sub-block, 255 bytes |
434 | … | <image data> | Image data, 255 bytes |
⋮ | Repeat for next blocks | ||
92C0 | 00 | End of sub-block chain for this frame | |
92C1 | 21 F9 | Graphic Control Extension for frame #2 | |
⋮ | Repeat for next frames | ||
EDABD | 21 F9 | Graphic Control Extension for frame #44 | |
⋮ | Image information and data for frame #44 | ||
F48F5 | 3B | Trailer: Last byte in the file, signaling EOF |
The animation delay for each frame is specified in the GCE in hundredths of a second. Some economy of data is possible where a frame need only rewrite a portion of the pixels of the display, because the Image Descriptor can define a smaller rectangle to be rescanned instead of the whole image. Browsers or other displays that do not support animated GIFs typically show only the first frame.
The size and color quality of animated GIF files can vary significantly depending on the application used to create them. Strategies for minimizing file size include using a common global color table for all frames (rather than a complete local color table for each frame) and minimizing the number of pixels covered in successive frames (so that only the pixels that change from one frame to the next are included in the latter frame). More advanced techniques involve modifying color sequences to better match the existing LZW dictionary, a form of lossy compression. Simply packing a series of independent frame images into a composite animation tends to yield large file sizes. Tools are available to minimize the file size given an existing GIF.
Metadata[edit]
Metadata can be stored in GIF files as a comment block, a plain text block, or an application-specific application extension block. Several graphics editors use unofficial application extension blocks to include the data used to generate the image, so that it can be recovered for further editing.
All of these methods technically require the metadata to be broken into sub-blocks so that applications can navigate the metadata block without knowing its internal structure.
The Extensible Metadata Platform (XMP) metadata standard introduced an unofficial but now widespread «XMP Data» application extension block for including XMP data in GIF files.[38] Since the XMP data is encoded using UTF-8 without NUL characters, there are no 0 bytes in the data. Rather than break the data into formal sub-blocks, the extension block terminates with a «magic trailer» that routes any application treating the data as sub-blocks to a final 0 byte that terminates the sub-block chain.
Unisys and LZW patent enforcement[edit]
In 1977 and 1978, Jacob Ziv and Abraham Lempel published a pair of papers on a new class of lossless data-compression algorithms, now collectively referred to as LZ77 and LZ78. In 1983, Terry Welch developed a fast variant of LZ78 which was named Lempel–Ziv–Welch (LZW).[39][40]
Welch filed a patent application for the LZW method in June 1983. The resulting patent, US4558302,[41] granted in December 1985, was assigned to Sperry Corporation who subsequently merged with Burroughs Corporation in 1986 and formed Unisys.[39] Further patents were obtained in the United Kingdom, France, Germany, Italy, Japan and Canada.
In addition to the above patents, Welch’s 1983 patent also includes citations to several other patents that influenced it, including:
- two 1980 Japanese patents from NEC’s Jun Kanatsu,[42][43]
- U.S. Patent 4,021,782 (1974) from John S. Hoerning,
- U.S. Patent 4,366,551 (1977) from Klaus E. Holtz, and
- a 1981 German patent from Karl Eckhart Heinz.[44][45]
In June 1984, an article by Welch was published in the IEEE magazine which publicly described the LZW technique for the first time.[46] LZW became a popular data compression technique and, when the patent was granted, Unisys entered into licensing agreements with over a hundred companies.[39][47]
The popularity of LZW led CompuServe to choose it as the compression technique for their version of GIF, developed in 1987. At the time, CompuServe was not aware of the patent.[39] Unisys became aware that the version of GIF used the LZW compression technique and entered into licensing negotiations with CompuServe in January 1993. The subsequent agreement was announced on 24 December 1994.[40] Unisys stated that they expected all major commercial on-line information services companies employing the LZW patent to license the technology from Unisys at a reasonable rate, but that they would not require licensing, or fees to be paid, for non-commercial, non-profit GIF-based applications, including those for use on the on-line services.[47]
Following this announcement, there was widespread condemnation of CompuServe and Unisys, and many software developers threatened to stop using GIF. The PNG format (see below) was developed in 1995 as an intended replacement.[39][40][46] However, obtaining support from the makers of Web browsers and other software for the PNG format proved difficult and it was not possible to replace GIF, although PNG has gradually increased in popularity.[39] Therefore, GIF variations without LZW compression were developed. For instance the libungif library, based on Eric S. Raymond’s giflib, allows creation of GIFs that followed the data format but avoided the compression features, thus avoiding use of the Unisys LZW patent.[48] A 2001 Dr. Dobb’s article described a way to achieve LZW-compatible encoding without infringing on its patents.[49]
In August 1999, Unisys changed the details of their licensing practice, announcing the option for owners of certain non-commercial and private websites to obtain licenses on payment of a one-time license fee of $5000 or $7500.[50] Such licenses were not required for website owners or other GIF users who had used licensed software to generate GIFs. Nevertheless, Unisys was subjected to thousands of online attacks and abusive emails from users believing that they were going to be charged $5000 or sued for using GIFs on their websites.[51] Despite giving free licenses to hundreds of non-profit organizations, schools and governments, Unisys was completely unable to generate any good publicity and continued to be condemned by individuals and organizations such as the League for Programming Freedom who started the «Burn All GIFs» campaign in 1999.[52][53]
The United States LZW patent expired on 20 June 2003.[54] The counterpart patents in the United Kingdom, France, Germany and Italy expired on 18 June 2004, the Japanese patents expired on 20 June 2004, and the Canadian patent expired on 7 July 2004.[54] Consequently, while Unisys has further patents and patent applications relating to improvements to the LZW technique,[54] LZW itself (and consequently GIF) have been free to use since July 2004.[55]
Alternatives[edit]
PNG[edit]
Portable Network Graphics (PNG) was designed as a replacement for GIF in order to avoid infringement of Unisys’ patent on the LZW compression technique.[39] PNG offers better compression and more features than GIF,[56] animation being the only significant exception. PNG is more suitable than GIF in instances where true-color imaging and alpha transparency are required.
Although support for PNG format came slowly, new web browsers support PNG. Older versions of Internet Explorer do not support all features of PNG. Versions 6 and earlier do not support alpha channel transparency without using Microsoft-specific HTML extensions.[57] Gamma correction of PNG images was not supported before version 8, and the display of these images in earlier versions may have the wrong tint.[58]
For identical 8-bit (or lower) image data, PNG files are typically smaller than the equivalent GIFs, due to the more efficient compression techniques used in PNG encoding.[59] Complete support for GIF is complicated chiefly by the complex canvas structure it allows, though this is what enables the compact animation features.
Animation formats[edit]
Videos resolve many issues that GIFs present through common usage on the web. They include drastically smaller file sizes, the ability to surpass the 8-bit color restriction, and better frame-handling and compression through codecs. Virtually universal support for the GIF format in web browsers and a lack of official support for video in the HTML standard caused GIF to rise to prominence for the purpose of displaying short video-like files on the web.
- MNG («Multiple-image Network Graphics») was originally developed as a PNG-based solution for animations. MNG reached version 1.0 in 2001, but few applications support it.
- APNG («Animated Portable Network Graphics») was proposed by Mozilla in 2006. APNG is an extension to the PNG format as alternative to the MNG format. APNG is supported by most browsers as of 2019.[60] APNG provides the ability to animate PNG files, while retaining backwards compatibility in decoders that cannot understand the animation chunk (unlike MNG). Older decoders will simply render the first frame of the animation.
- The PNG group officially rejected APNG as an official extension on 20 April 2007.[61]
- There have been several subsequent proposals for a simple animated graphics format based on PNG using several different approaches.[62] Nevertheless, APNG is still under development by Mozilla and is supported in Firefox 3.0[63][64] while MNG support was dropped.[65][66] APNG is currently supported by all major web browsers including Chrome (since version 59.0), Opera, Firefox and Edge.
- Embedded Adobe Flash objects and
- MPEG files were used on some websites to display simple video, but required the use of an additional browser plugin.
- WebM and
- WebP are in development and are supported by some web browsers.[67]
- Other options for web animation include serving individual frames using AJAX, or
- animating SVG («Scalable vector graphics») images using JavaScript or SMIL («Synchronized Multimedia Integration Language»).[citation needed]
- With the introduction of widespread support of the HTML5 video (
<video>
) tag in most web browsers, some websites use a looped version of the video tag generated by JavaScript functions. This gives the appearance of a GIF, but with the size and speed advantages of compressed video.
- Notable examples are Gfycat and Imgur and their GIFV metaformat, which is really a video tag playing a looped MP4 or WebM compressed video.[68]
- HEIF («High Efficiency Image File Format») is an image file format, finalized in 2015, which uses a discrete cosine transform (DCT) lossy compression algorithm based on the HEVC video format, and related to the JPEG image format. In contrast to JPEG, HEIF supports animation.[69]
- Compared to the GIF format, which lacks DCT compression, HEIF allows significantly more efficient compression. HEIF stores more information and produces higher-quality animated images at a small fraction of an equivalent GIF’s size.[70]
- VP9 only supports alpha compositing with 4:2:0 chroma subsampling[71] in the YUVA420 pixel format, which may be unsuitable for GIFs that combine transparency with rasterised vector graphics with fine color details.
- AV1 video codec or AVIF can also be used either as a video or a sequenced image.
Uses[edit]
In April 2014, 4chan added support for silent WebM videos that are under 3 MB in size and 2 min in length,[72][73] and in October 2014, Imgur started converting any GIF files uploaded to the site to video and giving the link to the HTML player the appearance of an actual file with a .gifv
extension.[74][75]
In January 2016, Telegram started re-encoding all GIFs to MPEG-4 videos that «require up to 95% less disk space for the same image quality.»[76]
See also[edit]
- AVIF
- Cinemagraph, a partially animated photograph often in GIF
- Clear GIF, a technique used to check content access
- Comparison of graphics file formats
- GIF art, a form of digital art associated with GIF
- GIFBuilder, early animated GIF creation program
- GNU plotutils (supports pseudo-GIF, which uses run-length encoding rather than LZW)
- Microsoft GIF Animator, historic program to create simple animated GIFs
- Software patent
References[edit]
- ^ a b c «Graphics Interchange Format, Version 87a». W3C. 15 June 1987. Archived from the original on 22 December 2018. Retrieved 13 October 2012.
- ^ a b c «Graphics Interchange Format, Version 89a». W3C. 31 July 1990. Archived from the original on 22 December 2018. Retrieved 6 March 2009.
- ^ «Online Art». Compute!’s Apple Applications. December 1987. p. 10. Retrieved 14 September 2016.
- ^ Holdener III, Anthony (2008). Ajax: The Definitive Guide: Interactive Applications for the Web. O’Reilly Media. ISBN 978-0596528386.
- ^ Furht, Borko (2008). Encyclopedia of Multimedia. Springer. ISBN 978-0387747248.
- ^ McHugh, Molly (29 May 2015). «You Can Finally, Actually, Really, Truly Post GIFs on Facebook». Wired. wired.com. Archived from the original on 30 May 2015. Retrieved 29 May 2015.
- ^ Perez, Sarah (29 May 2015). «Facebook Confirms It Will Officially Support GIFs». techcrunch.com. Archived from the original on 30 May 2015. Retrieved 29 May 2015.
- ^ «Introducing GIF Stickers». Instagram. 23 January 2018. Archived from the original on 12 December 2019. Retrieved 19 September 2019.
- ^ «Oxford Dictionaries USA Word of the Year 2012». OxfordWords blog. Oxford American Dictionaries. 13 November 2012. Archived from the original on 3 August 2014. Retrieved 1 May 2013.
- ^ Flood, Alison (27 April 2013). «Gif is America’s word of the year? Now that’s what I call an omnishambles». Books blog. The Guardian. London. Archived from the original on 1 December 2016. Retrieved 1 May 2013.
- ^ Olsen, Steve. «The GIF Pronunciation Page». Archived from the original on 25 February 2009. Retrieved 6 March 2009.
- ^ a b c «Gif’s inventor says ignore dictionaries and say ‘Jif’«. BBC News. 22 May 2013. Archived from the original on 27 June 2018. Retrieved 22 May 2013.
- ^ Buck, Stephanie (21 October 2014). «70 percent of people worldwide pronounce GIF with a hard g«. Mashable. Archived from the original on 23 December 2021. Retrieved 24 December 2021.
- ^ van der Meulen, Marten (22 May 2019). «Obama, SCUBA or gift?: Authority and argumentation in online discussion on the pronunciation of GIF«. English Today. 36 (1): 45–50.
- ^ «GIF». The American Heritage Abbreviations Dictionary, Third Edition. Houghton Mifflin Company. 2005. Archived from the original on 3 September 2011. Retrieved 15 April 2007.
- ^ «GIF». The Cambridge Dictionary of American English. Cambridge University Press. Archived from the original on 27 February 2014. Retrieved 19 February 2014.
- ^ «Gif — Definition from the Merriam-Webster Dictionary». Merriam-Webster Dictionary. Merriam-Webster, Incorporated. Archived from the original on 22 October 2013. Retrieved 6 June 2013.
- ^ «GIF». Oxford Dictionaries Online. Oxford University Press. Archived from the original on 12 October 2014. Retrieved 7 October 2014.
- ^ «gif noun — Definition, pictures, pronunciation and usage notes | Oxford Advanced Learner’s Dictionary». Oxford Learner’s Dictionaries. Archived from the original on 24 November 2020. Retrieved 6 February 2021.
- ^ «GIF | Definition of GIF by Oxford Dictionary». Lexico. Archived from the original on 13 February 2021. Retrieved 6 February 2021.
- ^ Stevenson, Angus, ed. (2010). Oxford Dictionary of English (3rd ed.). Oxford University Press. ISBN 9780199571123. OCLC 729551189.
- ^ The New Oxford American Dictionary (2nd ed.). Oxford University Press. 2005. p. 711.
- ^ The New Oxford American Dictionary (3rd ed.). 2012. (part of the Macintosh built-in dictionaries).
- ^ O’Leary, Amy (21 May 2013). «An Honor for the Creator of the GIF». The New York Times. Archived from the original on 22 May 2013. Retrieved 22 May 2013.
- ^ a b Rothberg, Daniel (4 December 2013). «‘Jeopardy’ wades into ‘GIF’ pronunciation battle». Los Angeles Times. Archived from the original on 6 December 2013. Retrieved 4 December 2013.
- ^ O’Leary, Amy (23 May 2013). «Battle Over ‘GIF’ Pronunciation Erupts». The New York Times. Archived from the original on 16 December 2013. Retrieved 5 December 2013.
- ^ Valinsky, Jordan (February 25, 2020). «Jif settles the great debate with a GIF peanut butter jar». CNN. Archived from the original on February 25, 2020. Retrieved February 25, 2020.
- ^ Marur, D.R.; Bhaskar, V. (March 2012). «2012 International Conference on Devices, Circuits and Systems (ICDCS)». Devices, Circuits and Systems (ICDCS). International Conference on Devices, Circuits and Systems (ICDCS). Karunya University; Coimbatore, India: IEEE. pp. 297–301. doi:10.1109/ICDCSyst.2012.6188724. ISBN 9781457715457. Archived from the original on 2 July 2017. Retrieved 11 March 2015.
- ^ S. Chin; D. Iverson; O. Campesato; P. Trani (2011). Pro Android Flash (PDF). New York: Apress. p. 350. ISBN 9781430232315. Archived (PDF) from the original on 2 April 2015. Retrieved 11 March 2015.
- ^ Bakhshi, Saeideh; Shamma, David A.; Kennedy, Lyndon; Song, Yale; de Juan, Paloma; Kaye, Joseph «Jofish» (7 May 2016). «Fast, Cheap, and Good: Why Animated GIFs Engage Us». Proceedings of the 2016 CHI Conference on Human Factors in Computing Systems: 575–586. doi:10.1145/2858036.2858532. S2CID 7417853. Retrieved 17 August 2022.
- ^ Highfield, Tim; Leaver, Tama (2016). «Instagrammatics and digital methods: studying visual social media, from selfies and GIFs to memes and emoji». Communication Research and Practice. 2 (1): 47–62. doi:10.1080/22041451.2016.1155332. S2CID 148538216. Retrieved 17 August 2022.
- ^ a b c Andreas Kleinert (2007). «GIF 24 Bit (truecolor) extensions». Archived from the original on 16 March 2012. Retrieved 23 March 2012.
- ^ a b Philip Howard. «True-Color GIF Example». Archived from the original on 22 February 2015. Retrieved 23 March 2012.
- ^ «Nullsleep — Jeremiah Johnson — Animated GIF Minimum Frame Delay Browser Compatibility Study». Archived from the original on 10 October 2014. Retrieved 26 May 2015.
- ^ «They’re different! How to match the animation rate of gif files accross [sic] browsers». Developer’s Blog. 14 February 2012. Archived from the original on 1 February 2017. Retrieved 15 June 2017.
- ^ Royal Frazier. «All About GIF89a». Archived from the original on 18 April 1999. Retrieved 7 January 2013.
- ^
Scott Walter (1996). Web Scripting Secret Weapons. Que Publishing. ISBN 0-7897-0947-3. - ^ «XMP Specification Part 3: Storage in Files» (PDF). Adobe. 2016. pp. 11–12. Archived (PDF) from the original on 25 February 2018. Retrieved 16 August 2018.
- ^ a b c d e f g Greg Roelofs. «History of the Portable Network Graphics (PNG) Format». Archived from the original on 7 March 2012. Retrieved 23 March 2012.
- ^ a b c Stuart Caie. «Sad day… GIF patent dead at 20». Archived from the original on 10 February 2012. Retrieved 23 March 2012.
- ^ US 4558302, Welch, Terry A., published 1985-12-10, assigned to Sperry Corp.
- ^ JP patent S5719857A, Kanatsu, Jiyun, «Data compression storage device», published 1982-02-02, assigned to Nippon Electric Corp.
- ^ JP patent S57101937A, Kanatsu, Jiyun, «Data storage device», published 1986-20-24, assigned to Nippon Electric Corp.
- ^ DE patent 3118676, Eckhart, Heinz Karl, «Verfahren zur Kompression redundanter Folgen serieller Datenelemente [Method for compressing redundant sequences of serial data elements]», published 1982-12-02
- ^ U.S. Patent 4,558,302
- ^ a b «The GIF Controversy: A Software Developer’s Perspective». Archived from the original on 23 August 2016. Retrieved 26 May 2015.
- ^ a b «Unisys Clarifies Policy Regarding Patent Use in On-Line Service Offerings». Archived from the original on 7 February 2007. – archived by League for Programming Freedom
- ^ «Libungif». Archived from the original on 13 April 2015. Retrieved 26 May 2015.
- ^ Cargill, Tom (1 October 2001). «Replacing a Dictionary with a Square Root». Dr. Dobb’s Journal. Archived from the original on 28 June 2017. Retrieved 20 January 2017.
- ^ «LZW Software and Patent Information». Archived from the original on 8 June 2009. Retrieved 31 January 2007. – clarification of 2 September 1999
- ^ Unisys Not Suing (most) Webmasters for Using GIFs Archived 10 May 2017 at the Wayback Machine – Slashdot investigation into the controversy
- ^ «Burn All GIFs Day». Archived from the original on 13 October 1999.
- ^ Burn All GIFs Archived 3 February 2007 at the Wayback Machine – A project of the League for Programming Freedom (latest version)
- ^ a b c «License Information on GIF and Other LZW-based Technologies». Archived from the original on 2 June 2009. Retrieved 26 April 2005.
- ^ «Why There Are No GIF Files on GNU Web Pages». Free Software Foundation. Archived from the original on 19 May 2012. Retrieved 19 May 2012.
- ^ «PNG versus GIF Compression». 31 March 2007. Archived from the original on 15 July 2009. Retrieved 8 June 2009.
- ^ «AlphaImageLoader Filter». Microsoft. Archived from the original on 3 October 2014. Retrieved 26 May 2015.
- ^ «What’s New in Internet Explorer 7». MSDN. Archived from the original on 1 March 2009. Retrieved 6 March 2009.
- ^ «PNG Image File Format». Archived from the original on 14 June 2009. Retrieved 8 June 2009.
- ^ «Can I use… Support tables for HTML5, CSS3, etc». caniuse.com. Archived from the original on 19 February 2018. Retrieved 10 April 2020.
- ^ «VOTE FAILED: APNG 20070405a». SourceForge mailing list. 20 April 2007. Archived from the original on 13 February 2013. Retrieved 14 July 2013.
- ^ «Discussion for a simple «animated» PNG format». Archived from the original on 26 February 2009. Retrieved 12 July 2011.
- ^ «APNG Specification». Archived from the original on 5 July 2010. Retrieved 26 May 2015.
- ^ «Mozilla Labs » Blog Archive » Better animations in Firefox 3». Archived from the original on 7 March 2016. Retrieved 3 February 2016.
- ^ «195280 – Removal of MNG/JNG support». Archived from the original on 25 February 2021. Retrieved 26 May 2015.
- ^ «18574 – (mng) restore support for MNG animation format and JNG image format». Archived from the original on 17 March 2021. Retrieved 26 May 2015.
- ^ «Chromium Blog: Chrome 32 Beta: Animated WebP images and faster Chrome for Android touch input». Blog.chromium.org. 21 November 2013. Archived from the original on 17 July 2018. Retrieved 1 February 2014.
- ^ «Introducing GIFV — Imgur Blog». imgur.com. 9 October 2014. Archived from the original on 14 December 2014. Retrieved 14 December 2014.
- ^ Thomson, Gavin; Shah, Athar (2017). «Introducing HEIF and HEVC» (PDF). Apple Inc. Archived (PDF) from the original on 19 January 2020. Retrieved 5 August 2019.
- ^ «HEIF Comparison — High Efficiency Image File Format». Nokia Technologies. Archived from the original on 25 July 2019. Retrieved 5 August 2019.
- ^ «#3271 (Allow using additional pixel formats with libvpx-vp9) – FFmpeg». trac.ffmpeg.org. Archived from the original on 16 June 2020. Retrieved 10 April 2020.
- ^ Dewey, Caitlin. «Meet the technology that could make GIFs obsolete». The Washington Post. Archived from the original on 11 May 2015. Retrieved 4 February 2015.
- ^ «WebM support on 4chan». 4chan Blog. Archived from the original on 6 April 2014. Retrieved 4 February 2015.
- ^ «Introducing GIFV». Imgur. 9 August 2014. Archived from the original on 5 May 2020. Retrieved 21 July 2016.
- ^ Allan, Patrick (9 October 2014). «Imgur Revamps GIFs for Faster Speeds and Higher Quality with GIFV». Lifehacker. Archived from the original on 3 February 2015. Retrieved 4 February 2015.
- ^ «GIF Revolution». Official Telegram Blog. 4 January 2016. Archived from the original on 10 January 2016. Retrieved 4 January 2016.
External links[edit]
- The GIFLIB project
- spec-gif89a.txt GIF 89a specification on w3.org
- GIF 89a specification reformatted into HTML
- LZW and GIF explained
- Animated GIFs: a six-minute documentary produced by Off Book (web series)
- GifCities (The GeoCities Animated GIF Search Engine)
Содержание
- 1 Русский
- 1.1 Морфологические и синтаксические свойства
- 1.2 Произношение
- 1.3 Семантические свойства
- 1.3.1 Значение
- 1.3.2 Синонимы
- 1.3.3 Антонимы
- 1.3.4 Гиперонимы
- 1.3.5 Гипонимы
- 1.4 Родственные слова
- 1.5 Этимология
- 1.6 Фразеологизмы и устойчивые сочетания
- 1.7 Перевод
- 1.8 Библиография
Русский[править]
В Викиданных есть лексема гифка (L101261). |
Морфологические и синтаксические свойства[править]
падеж | ед. ч. | мн. ч. |
---|---|---|
Им. | ги́фка | ги́фки |
Р. | ги́фки | ги́фок |
Д. | ги́фке | ги́фкам |
В. | ги́фку | ги́фки |
Тв. | ги́фкой ги́фкою |
ги́фками |
Пр. | ги́фке | ги́фках |
ги́ф—ка
Существительное, неодушевлённое, женский род, 1-е склонение (тип склонения 3*a по классификации А. А. Зализняка).
Корень: -гиф-; суффикс: -к; окончание: -а.
Произношение[править]
- МФА: ед. ч. [ˈɡʲifkə], мн. ч. [ˈɡʲifkʲɪ]
Семантические свойства[править]
Значение[править]
- комп. жарг. графический файл в формате GIF ◆ Отсутствует пример употребления (см. рекомендации).
Синонимы[править]
- гифак, гифчик
Антонимы[править]
Гиперонимы[править]
- файл
Гипонимы[править]
Родственные слова[править]
Ближайшее родство | |
Этимология[править]
Происходит от англ. GIF.
Фразеологизмы и устойчивые сочетания[править]
Перевод[править]
Список переводов | |
|
Библиография[править]
|
Для улучшения этой статьи желательно:
|
Семейство форматов файлов растровых изображений
Расширение имени файла | .gif |
---|---|
Тип интернет-носителя | image / gif |
Код типа | GIFf |
Универсальный идентификатор типа (UTI) | com.compuserve.gif |
Магическое число | GIF87a / GIF89a |
Разработано | CompuServe |
Первоначальный выпуск | 15 июня 1987 г.; 33 года назад (1987-06-15) |
Последний выпуск | 89a. (1989; 31 год назад (1989)) |
Тип формата | без потерь растровое изображение формат изображения |
Веб-сайт | www.w3.org / Графика / GIF / spec-gif89a.txt |
Формат обмена графикой (GIF ; или ) — это точечный рисунок формат изображения, который был разработан командой поставщика онлайн-услуг CompuServe во главе с американским ученым-компьютерщиком Стивом Уилхайтом 15 июня 1987 г. С тех пор он он представителем в World Wide Web благодаря широкой поддержке и переносимости между приложениями и низкими системами.
Формат поддерживает до 8 бит на пиксель для каждого изображения, что позволяет изображению ссылаться на свою собственную палитру, содержащую до 256 различных цветов, выбранных из 24 -бит цветовое пространство RGB. Он также поддерживает анимацию и позволяет использовать отдельную палитру до 256 цветов для каждого кадра. Эти ограничения палитры делают GIF менее подходящим для воспроизведения цветных фотографий и других изображений с цветовыми градиентами, но хорошо подходят для более простых изображений, таких как графика или логотипы со сплошными цветовыми областями. В отличие от видео, формат файла GIF не поддерживает звук.
Изображения GIF сжимаются с использованием метода Лемпеля — Зива — Велча (LZW) сжатие данных без потерь, чтобы уменьшить размер файла без ухудшения визуального качества. Этот метод сжатия был запатентован в 1985 году. Разногласия по поводу лицензионного соглашения между держателем патента на программное обеспечение, Unisys и CompuServe в 1994 году стимулировали программу Portable Network Graphics (PNG) стандартный. К 2004 году срок действия всех патентов истек.
Содержание
- 1 История
- 2 Терминология
- 2.1 Произношение GIF
- 3 Использование
- 4 Формат файла
- 5 Палитры
- 5.1 Истинный цвет
- 6 Пример файла GIF
- 6.1 Кодирование изображения
- 6.2 Декодирование изображения
- 6.3 Длина кода LZW
- 6.4 Несжатый GIF
- 7 Пример сжатия
- 8 Чередование
- 9 Анимированный GIF
- 10 Метаданные
- 11 Защита патентов Unisys и LZW
- 12 Альтернативы
- 12.1 PNG
- 12.2 Форматы анимации
- 12.2.1 Использование
- 13 См. Также
- 14 Ссылки
- 15 Внешние ссылки
История
CompuServe представил GIF 15 июня 1987 г., чтобы обеспечить формат цветного изображения для загрузки файлов, заменив их более ранний формат кодирования длин серий (РЛЭ), который был только черно-белым. GIF стал популярным, потому что в нем использовалось сжатие данных LZW, которое было более эффективным, чем кодирование длинных серий, в котором используются форматы, популярные тем, используемые в PCX и MacPaint, и поэтому довольно большие изображения можно было загрузить за достаточно короткое время, даже с очень медленными модемами .
Исходная версия GIF называлась 87a . В 1989 году CompuServe выпустила расширенную версию под названием 89a, в которой добавлена поддержка задержек анимации (несколько изображений в потоке уже поддерживались в 87a), прозрачные цвета фона и хранилища метаданных для приложений. Спецификация 89a также поддерживает включение текстовых меток в виде текста (не встраивание их в графические данные), но, поскольку имеется небольшой контроль над отображаемыми шрифтами, эта функция широко не используется. Две версии можно отличить, посмотрев на первые шесть файлов («магическое число » или подпись), которые при интерпретации как ASCII прочтите «GIF87a» и «GIF89a «соответственно.
CompuServe использует используемые внедрение GIF, предоставляя загружаемые утилиты преобразования для многих компьютеров. К декабрю 1987 года, например, пользователь Apple IIGS мог просматривать изображения, созданные на Atari ST или Commodore 64. GIF был одним из первых двух форматов изображений, которые широко использовались на веб-сайтах, второй — черно-белый XBM.
. В сентябре 1995 года в Netscape Navigator 2.0 добавлена возможность для анимированных GIF в цикле.
Функция сохранения нескольких изображений в одном файле с управляющими данными широко используется в Интернете для создания простых анимаций. Дополнительная функция развертки, которая хранит строки не по порядку, таким образом, что даже частично загруженное изображение было несколько узнаваемым, также создало GIF, поскольку пользователь мог прервать загрузку, если это было не то, что требовалось.
В мае 2015 года Facebook добавил поддержку GIF. В январе 2018 года Instagram также добавил стикеры в формате GIF в режим истории.
Терминология
Как существующее, слово GIF встречается в новых редакциях многих словрей. В 2012 году американское крыло Oxford University Press признало GIF как глагол, означающий «создать файл GIF», поскольку в «GIFing был идеальным средством для обмена сценами». из Летних Олимпийских игр «. Лексикографы прессы проголосовали за его словом года, заявив, что GIF превратились в« инструменты с серьезными приложениями, включая исследования и журналистику ».
Произношение GIF
Юмористическое изображение объявляя о запуске Белого дома Tumblr предлагает произносить GIF с жесткой буквой «G».
Создатели формата произнесли это слово как «jif» с мягкий «G» как в «спортзал». Стив Уилхайт говорит, что предполагаемое произношение намеренно перекликается с американским маслом брендом Jif, и сотрудники CompuServe часто говорили: «Разборчивые разработчики выбирают GIF», подделывая его телевизионные ролики. Слово теперь также широко произносится с твердым «G» В 2017 году неофициальный опрос на веб-сайте программирования Stack Overflow некоторое количество численное предпочтение жесткому прои зношению «G», особенно среди респондентов Восточной Европы, хотя были обнаружены как мягкое- «G», так и произнесение каждой буквы отдельно. быть популярным в азиатских и опасных странах.
Словарь американского наследия цитирует оба, указав «jif» в качестве основного произношения, в то время как Кембриджский словарь Американский английский предлагает только жесткое — «G» произношение. Словарь Merriam- Webster и OED цитируют оба произношения, но помещают «gif» в позицию по умолчанию (« ˈgif, jif »). Новый оксфордский американский словарь дал только «jif»
Разногласия по поводу произношения к горячим дебатам в Интернете, но обновил его до «jif, gif» в 3-м издании. Премия Уэбби 2013 года Уилхайт отказался от твердого произношения «G», и его речь привела к 17000 публикаций в Twitter и 50 новостей статьи Белый дом и телепрограмма Jeopardy ! также участвовали в дебатах в течение 2013 года.
В феврале 2020 года The JM Smucker Company, владельцы бренда арахисового масла Jif в партнерстве с базой данных анимированных изображений и поисковой системой Giphy для выпуска баночки с арахисом Jif ограниченным тиражом «Jif vs. GIF» (с пометкой как #JIFvsGIF) сливочное масло, на этикетке которого юмористически объявляется, что мягкое произношение «G» относится исключительно к арахисовому маслу, а GIF — произносится исключительно с жестким произношением «G».
Использование
- Подходят GIF-файлы для штриховых рисунков с острыми краями и ограниченного количества цветов, например логотипов. Это позволяет использовать сжатие без потерь формата.
- GIF-файлы можно использовать для хранения данных с низким уровнем цвета спрайтов для игр.
- GIF-файлы можно использовать для небольших анимаций и видеоклипов с низким разрешением.
- GIF-файлы можно использовать в качестве реакции при обмене сообщениями в Интернете, использовать для передачи эмоций и чувств вместо слов
- Популярные социальные сети, таких как Tumblr, Facebook и Twitter.
Формат файла
Файл: Empty.gif в
Концептуально файл GIF данной графической области фиксированного размера («логический экран») заполненный нулями или более «изображениями». Многие файлы содержат одно изображение, занимающее весь логический экран. Другие делят логический экран на отдельные фрагменты изображения. Изображения могут также функционировать как кадры анимации в анимированном файле GIF, но, опять же, они не должны заполнять весь логический экран.
Файлы GIF начинаются с заголовка фиксированной длины («GIF87a» или «GIF89a»), указывающей версию логического файла, за которым следует дескриптор размера экрана фиксированной длины, указывающий в пикселях и другие характеристики логического экрана. Дескриптор экрана может также указывать наличие и размер Глобальной таблицы цветов, которая следует за следующей, если она есть.
00000000 47 49 46 38 39 61 01 00 01 00 80 00 00 00 00 00 | GIF89a.......... | 00000010 ff ff ff 21 f9 04 01 00 00 00 00 2c 00 00 00 00 |...!.......,.... | 00000020 01 00 01 00 00 02 01 44 00 3b |....... D.; | 0000002a
После этого файла делится на сегменты, каждый из представленных 1-байтовым сигналом:
- Изображение (вводится 0x2C, запятая ASCII
','
) - Блок расширения (вводится 0x21, восклицательный знак ASCII
'!'
) - Конечный конец (один байт значения 0x3B, точка с запятой ASCII
';'
), который должен быть последним байтом файла.
Изображение начинается с дескриптора изображения фиксированной длины, который может Указать следующие изображения: один байт, указывающий разрядность незакодированных символов (указывающий размер не 2 бита, даже для двухцветных изображений). субблоков, используются данные в кодировке LZW.
Блок расширяющих расширений (блоки, которые «определяют» 87a через механизм, уже определены в спецификации 87a), включает контрольную точку, дополнительное байта, определяющ его тип расширения, и связанного списка подблоков информация о расширении. модифицирующие изображение (например, Graphic Control Extension, определяющее необязательное время задержки анимации и необязательный прозрачный цвет фона) должны непосредственно предшествовать сегменту с изображением, на которое они указанные.
Связанные списки, используемые данные и блоками расширения, состоят из серии субблоков, каждый субблок с байта, указывающее количество байтов данных в субблоке (от 1 до 255). Последовательность субблоков заканчивается пустым субблоком (нулевым байтом).
Эта структура позволяет анализировать файл, даже если не все части понятны. GIF с пометкой 87a может содержать блоки расширения; Цель состоит в том, чтобы декодировать файлы без функций, охватываемых расширениями, которые он не понимает.
Полная информация о формате файла содержится в спецификации GIF.
Палитры
Пример изображения GIF, сохраненного с веб-палитрой и сшиты с использованием метода Флойда — Стейнберга. Из-за меньшего количества цветов в изображении проблемы с отображением.
GIF основан на палитре: которая используется в изображении (кадре) в файле, имеют свои значения RGB, в таблица палитры, которая может содержать до 256 записей, а данные для изображения к цветам по их индексам (0–255) в таблице палитр. Цветовые определения в палитре могут быть взяты из цветового пространства из миллионов оттенков (2 оттенка, 8 бит для каждого основного), но максимальное количество цветов, которое может использовать кадр, составляет 256. Это ограничение кажется разумным, когда был разработан GIF, потому что мало кто мог бы себе оборудование для одновременного отображения большего количества цветов. Для простой графики, штриховых рисунков, мультфильмов и фотографий в градациях серого обычно требуется менее 256 цветов.
Каждый кадр может обозначать один индекс как «цвет прозрачного фона»: любой пиксель, которому назначен этот индекс, принимает цвет пикселя в той же позиции, который может быть определен предыдущим кадром анимация.
Многие методы, вместе называемые дизерингом, были разработаны для аппроксимации более широкого диапазона цветов с помощью небольшого цветового палитры с использованием пикселей двух или более цветов для приближения промежуточных цветов. Эти методы приносят в жертву пространственное разрешение, приблизиться к более глубокому цветовому разрешению. Хотя дизеринг не является отцовской установкой GIF. Это часто не идеальное решение для изображений GIF, потому что это изображение нечеткое изображение на экране, а также изображение нечеткое изображение, используемое против основной цели GIF.
В первые дни графических веб-браузеров графические карты с 8-битными буферами (позволяющие только 256 цветов) были обычным явлением, и довольно часто было принято создавать изображения с использованием веб-палитры. Это обеспечивало предсказуемое отображение, но сильно ограничивало выбор цветов. Когда 24-битный цвет стал нормой, палитры вместо этого были заполнены оптимальными цветами для отдельных изображений.
Небольшой таблицы цветов может быть достаточно для небольших изображений, а сохранение небольшого размера таблицы цветов позволяет загружать файл быстрее. Обе в спецификации 87a и 89 допускают цветовые таблицы из 2 цветов для любого n от 1 до 8. Большинство графических приложений будут читать и отображать изображения GIF с любыми из этих таблиц; но некоторые не все размеры при изображений. Широко поддерживаются таблицы с 2, 16 и 256 цветов.
True color
Анимированный GIF, показывающий технику отображения более стандартного предела в 256 цветов
Хотя GIF никогда не используется для изображений true color, это возможно сделать так. Изображение в формате GIF может в себя несколько блоков изображения, каждый из которых может иметь свою 256-цветовую палитру, и блоки можно размещать мозаикой для создания полного изображения. В качестве альтернативы, спецификация GIF89a представила идею «прозрачного» цвета, где каждый блок изображения может включить свой собственный палитру из 255 видимых цветов плюс один прозрачный. Полное изображение может быть создано через прозрачные части изображения.
Чтобы показать полноцветное изображение в формате GIF, исходное изображение должно быть разбито на более мелкие области, содержащее не более 255 или 256 различных цветов. Каждая из этих систем используется как отдельный блок изображения со стандартной палитрой, и когда блоки изображения вместе (либо мозаикой, либо наслоением частично прозрачных блоков изображения), появляется полное полноцветное изображение. Например, разбиение изображения на плитку размером 16 на 16 пикселей (всего 256 пикселей) гарантирует, что ни одна плитка не будет иметь больше, чем локальный предел палитры в 256 цветов, хотя можно использовать плитки большего размера и объединить похожие цвета, что к некоторой потере цвета
Так как каждый блок изображения может иметь собственную локальную таблицу цветов, файл GIF, набор блоков изображения, может быть очень большим, что ограничивает полезность полноцветных файлов GIF. Кроме того, не все программы рендеринга GIF правильно обрабатывают мозаичные или многослойные изображения. Многие программы рендеринга интерпретируют плитки или слои как кадры анимации и отображают их как бесконечную анимацию, большинство веб-браузеров автоматически отображают кадры с задержкой 0,1 секунды или более.
Пример файла GIF
Примерное изображение (увеличенное), фактический размер 3 пикселя в ширину и 5 в высоту
Байты D h до 30C h в определяют палитру из 256 цветов.
Microsoft Paint сохраняет маленькое черно-белое изображение как следующий файл GIF. Paint не оптимально использует GIF; из-за неоправданно большой таблицы цветов (хранение всех 256 цветов вместо используемых 2) и ширины символа этот файл GIF не является эффективным 15-пиксельным изображения (проиллюстрировано выше в увеличенном масштабе).
Хотя блок Graphic Control Extension объявляет индекс цвета 16 (шестнадцатеричный 10) прозрачным, этот индекс не используется в изображении. Единственные индексы цвета, появляющиеся в данных изображения, — это десятичные 40 и 255, которые Глобальная таблица цветов отображает на черный и белый соответственно.
Обратите внимание, что шестнадцатеричные числа в следующих таблицах расположены в порядке little-endian байтов, как предписывает спецификация формата.
байт # шестнадцатеричный текст или (шестнадцатеричное) значение Значение 0: 47 49 46 38 39 61 GIF89a Заголовок Логический дескриптор экрана 6: 03 00 3 - логическая ширина экрана в пикселях 8: 05 00 5 - логическая высота экрана в пикселях A: F7 - GCT следует для 256 цветов с разрешением 3 × 8 бит / первичный; 3 младших бита представляют битовую глубину минус 1, самый высокий истинный бит означает, что присутствует GCT B: 00 0 - цвет фона # 0 C: 00 - соотношение сторон пикселя по умолчанию Таблица глобальных цветов RGB D: 00 00 00 0 0 0 - цвет # 0 черный 10: 80 00 00 128 0 0 - цвет # 1:: 85: 00 00 00 0 0 0 - цвет # 40 черный:: 30A: FF FF FF 255 255 255 - цвет # 255 белый 30D: 21 F9 Graphic Control Extension (поля комментариев предшествуют этому в большинстве файлов) 30F: 04 4 - 4 байта данных GCE следуют за 310: 01 - есть прозрачный цвет фона (битовое поле; самый низкий бит означает прозрачность) 311: 00 00 - задержка для анимации в сотых долях секунды: не используется 313: 10 16 - цвет # 16 прозрачный 314: 00 - конец блока GCE 315: 2C Дескриптор изображения 316: 00 00 00 00 (0,0) - положение NW угла изображения на логическом экране 31A: 03 00 05 00 (3,5) - ширина и высота изображения в пикселях 31E: 00 - нет локальной таблицы цветов 31F: 08 8 Начало изображения - минимальный размер кода LZW 320: 0B 11 - 11 байтов LZW кодированные данные изображения следуют 321: 00 51 FC 1B 28 70 A0 C1 83 01 01 32C: 00 - конец данных изображения 32D: 3B Знак конца файла GIF
Кодирование изображения
Данные пикселей изображения, сканированные по горизонтали сверху слева, преобразуется с помощью LZW-кодирования в коды, которые затем преобразуются в байты для хранения в файле. Коды пикселей обычно не соответствуют 8-битному размеру байтов, поэтому коды упаковываются в байты по схеме «little-Endian»: младший значащий бит первого кода сохраняется в младшем значащем бите первый байт, биты старшего разряда кода в биты старшего порядка байта, при необходимости переходящие в биты младшего разряда следующего байта. Каждый последующий код сохраняется, начиная с младшего значащего бита, который еще не используется.
Этот поток байтов сохраняется в файле в виде серии «субблоков». Каждый субблок имеет максимальную длину 255 байтов и имеет префикс байта, указывающий количество байтов данных в субблоке. Последовательность субблоков заканчивается пустым субблоком (один нулевой байт, указывающий субблок с нулевыми байтами данных).
Для примера изображения выше обратимое отображение между 9-битными кодами и байтами показано ниже.
9-битный код. (шестнадцатеричный) | Двоичный | Байт. (шестнадцатеричный) |
---|---|---|
00000000| | 00 | |
100 | ||
0101000 | 1 | 51 | |
028 | ||
111111|00 | FC | |
0FF | ||
00011|011 | 1B | |
103 | ||
0010 | 1000 | 28 | |
102 | ||
011|10000 | 70 | |
103 | ||
10|100000 | A0 | |
106 | ||
1 | 1000001 | C1 | |
107 | ||
|10000011 | 83 | |
101 | ||
00000001 | 01 | |
0000000 | 1 | 01 |
Безопасное небольшое сжатие: цвета пикселей, устанавливают 15 байтами, точно 12 байтами кода, включая управляющие коды. Ниже показан процесс кодирования 9-битных кодов. В строке накапливаются номера цветов из палитры без действия вывода, пока локальная строка может быть найдена в кодовой таблице. Существует специальная обработка двух пикселей, которые поступают до того, как таблица вырастет от своего первоначального размера путем добавления строк. После каждого выходного кода локальная строка инициализируется последним кодом пикселя (который не может быть включен в выходной код).
Таблица 9-битная строка ->код код Действие # 0 | 000h Инициализировать корневую таблицу палитры 9-битных кодов | : цвета | : # 255 | 0FFh clr | 100ч конец | 101h | 100 ч четких пикселей локально | цветовая палитра строка | ЧЕРНЫЙ # 40 28 | 028h 1-й пиксель всегда выводить БЕЛЫЙ # 255 FF | Строка из таблицы 28 FF | 102h Всегда первую строку в таблицу FF | Инициализировать локальную ткань WHITE # 255 FF FF | Строка не найдена в таблице | 0FFh - код вывода предыдущей строки FF FF | 103h - добавить последнюю строку в таблицу FF | - инициализировать локальную силу WHITE # 255 FF FF | Строка найдена в таблице BLACK # 40 FF FF 28 | Строка не найдена в таблице | 103h - код вывода предыдущей строки FF FF 28 | 104h - добавить последнюю строку в таблицу 28 | - инициализировать локальную силу WHITE # 255 28 FF | Строка найдена в таблице WHITE # 255 28 FF FF | Строка не найдена в таблице | 102h - код вывода предыдущей строки 28 FF FF | 105h - добавить последнюю строку в таблицу FF | - инициализировать локальную силу WHITE # 255 FF FF | Строка найдена в таблице WHITE # 255 FF FF FF | Строка не найдена в таблице | 103h - код вывода предыдущей строки FF FF FF | 106h - добавить последнюю строку в таблицу FF | - инициализировать локальную силу WHITE # 255 FF FF | Строка найдена в таблице WHITE # 255 FF FF FF | Строка найдена в таблице WHITE # 255 FF FF FF FF | Строка не найдена в таблице | 106h - код вывода предыдущей строки FF FF FF FF | 107h - добавить последнюю строку в таблицу FF | - инициализировать локальную силу WHITE # 255 FF FF | Строка найдена в таблице WHITE # 255 FF FF FF | Строка найдена в таблице WHITE # 255 FF FF FF FF | В таблице найдена строка Нет больше пикселей 107h - выходной код для последней строки 101h Конец
Для наглядности визуальной таблицы выше как построенная из строк увеличиваемой длины. Эта схема может работать, но таблица потребляет непредсказуемый объем памяти. В практике можно сохранить память, заметив, каждая новая сохраняемая строка из ранее сохраненной строки, дополненной символом. Экономно хранить в каждом адресе только два слова: существующий адрес и один символ.
Алгоритм LZW требует поиска в таблице каждого пикселя. Линейный поиск по 4096 адресам замедлит кодирование. На практике коды содержат в порядке числовых значений; это позволяет выполнять каждый поиск с помощью SAR (регистр последовательного приближения, который используется в некоторых АЦП ) только с 12 сравнениями величин. Для этой эффективности дополнительной таблицы для преобразования между кодами и факимическими адресами памяти; дополнительное обслуживание таблицы необходимо только тогда, когда используется новый код, который происходит с большей скоростью, чем пиксельная.
Декодирование изображения
Декодирование начинается с отображения сохраненных байтов обратно в 9-битные коды. Они декодируются для восстановления цветов пикселей, как показано ниже. Таблица, идентичная той, которая используется в кодировщике, создается добавление строк по следующим правилам:
Да | добавить строку для локального кода, за которой следует кодовая строка для входящего кода |
No | ввести строку для локального кода, за которой следует копия своего первого байта |
shift 9-битный ---->Пиксель таблицы таблицы код code code ->строка Цвет палитры Действие 100h 000h | # 0 Инициализировать корневую таблицу 9-битных кодов: | палитра: | цвета 0FFh | # 255 100h | clr 101h | конец 028h | # 40 ЧЕРНЫЙ Декодировать 1-й пиксель 0FFh 028h | Входящий код найден в таблице | # 255 WHITE - строка вывода из таблицы 102h | 28 FF - добавить в таблицу 103h 0FFh | Входящий код не найден в таблице 103h | FF FF - в таблицу | - строка вывода из таблицы | # 255 БЕЛЫЙ | # 255 БЕЛЫЙ 102h 103h | Входящий код найден в таблице | - строка вывода из таблицы | # 40 ЧЕРНЫЙ | # 255 БЕЛЫЙ 104h | FF FF 28 - добавить в таблицу 103h 102h | Входящий код найден в таблице | - строка вывода из таблицы | # 255 БЕЛЫЙ | # 255 БЕЛЫЙ 105h | 28 FF FF - добавить в таблицу 106h 103h | Входящий код не найден в таблице 106h | FF FF FF - в таблицу | - строка вывода из таблицы | # 255 БЕЛЫЙ | # 255 БЕЛЫЙ | # 255 БЕЛЫЙ 107h 106h | Входящий код не найден в таблице 107h | FF FF FF FF - в таблицу | - строка вывода из таблицы | # 255 БЕЛЫЙ | # 255 БЕЛЫЙ | # 255 БЕЛЫЙ | # 255 БЕЛЫЙ 101h | Конец
Длина кода LZW
Более короткое кодовое обозначение для палитр, меньших, чем 256 цветов в примере. Если палитра включает только из 64 цветов (так что цветовые индексы имеют ширину 6 бит), символы могут находиться в диапазоне от 0 до 63, ширина символа может быть принята равной 6 битам с кодами, начинающимися с 7 бит. Фактически, длина символа не обязательно должна соответствовать размеру палитры: до тех, пока декодируются всегда меньше количества цветов в палитре, символы имеют любую ширину от 2 до 8, размер палитры — любую степень 2. от 2 до 256., если используются только первые четыре цвета (значения от 0 до 3) палитры, символы можно считать шириной 2 бита с кодами, начинающимися с 3 бита.
И наоборот, ширину символа можно установить равной 8, даже если используются только значения 0 и 1; для этих данных потребуется только двухцветная таблица. Хотя нет смысла кодировать файл таким образом, нечто подобное обычно происходит с двухцветными изображениями: минимальная ширина символа соответствует 2, даже если используются только значения 0 и 1.
Кодовая таблица изначально содержит коды, которые на один бит длиннее, чем размер символа, чтобы учесть два специальных кода кода и коды для строк, которые добавляются во время процесса. Когда таблица заполнена, длина кода увеличивается, чтобы освободить место для большего количества строк, до кода 4095 = FFF (шестнадцатеричный). По тому, как он отслеживает эту таблицу длины кода и может соответственно распаковывать входящие байты.
Несжатый GIF
Несжатый GIF размером 46 × 46 с 7-битными символами (128 цветов, 8-битные коды). Щелкните изображение для объяснения кода.
Процесс кодирования GIF можно изменить, чтобы создать файл без сжатия LZW, который по-прежнему можно просматривать как изображение GIF. Этот метод был введен как способ избежать нарушения патентных прав. Несжатый GIF также может быть промежуточным форматом для программиста графики, поскольку отдельные пиксели доступны для чтения или рисования. Несжатый файл GIF можно преобразовать в обычный файл GIF, просто пропустив его через редактор изображений.
Модифицированный метод кодирования игнорирует построение таблицы LZW и выдает только коды для CLEAR и STOP. Это дает более простое кодирование (соответствие 1 к 1 между кодовыми значениями и кодом палитры), но жертвует всем сжатием: каждый пиксель в изображении генерирует выходной код, указывающий его индекс цвета. При обработке несжата GIF стандартному декодеру GIF не запрещается записывать строки в свою таблицу словаря, поскольку это вызывает другую упаковку битов в байты.
Если символы делятся n, коды ширины n + 1 естественным образом идут на два блока: нижний блок из 2 кодов для кодирования одиночных символов и верхний блок из 2 кодов, которые будут кодировать для последовательности длиной больше единиц. Из этого верхнего блока уже приняты первые два кода: 2 для CLEAR и 2 + 1 для STOP. Также необходимо запретить декодеру последний код в верхнем блоке, 2-1, потому что, когда декодер заполняет этот код, увеличивает ширину кода. Таким образом, в верхнем блоке декодеру доступны 2–3 кода, которые не вызывают увеличения ширины кода. Введет запись в таблицу при получении первого кода от кодировщика, создает запись для каждого последующего кода. Таким образом, кодер может генерировать 2–2 кода, не вызывая увеличения ширины кода. Следовательно, кодировщик должен выдавать дополнительные коды CLEAR с интервалами 2–2 кода или меньше, чтобы декодер сбросил словарь кодирования. Стандарт GIF позволяет вставлять такие дополнительные коды ОЧИСТИТЬ данные изображения в любое время. Поток составных данных разделен на подблоки, каждый из которых содержит от 1 до 255 байтов.
Для примера изображения 3 × 5, приведенного выше, следующие 9-битные коды указать «очистить» (100), за которыми следуют пиксели изображения в порядке и «стоп» (101).
9-битные коды: 100 028 0FF 0FF 0FF 028 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 0FF 101
После того, как вышеуказанные коды в байтах, несжатый файл отличается от сжатого. файл таким образом:
: 320: 14 20 20 байт несжатых изображений следуют 321: 00 51 FC FB F7 0F C5 BF 7F FF FE FD FB F7 EF DF BF 7F 01 01335: 00 - конец:
Пример сжатия
Тривиальный пример большого изображения сплошного цвета демонстрируетие LZW пример длины, используемое в файлах GIF.
Код | Пиксели | Примечания | |||
---|---|---|---|---|---|
№. Ni | Значение. Ni+ 256 | Длина. (биты) | Этот код. Ni | Накопленный. Ni(Ni+ 1) / 2 | Отношения, использующие N i, применяются только к пикселям одного и того же цвета. до ввода таблицы кодирования. |
0 | 100h | 9 | Очистить кодовую таблицу | ||
1 | FFh | 1 | 1 | Цвет верхнего левого пикселя выбран как. наивысший индекс 256-цветной палитры | |
2 | 102h | 2 | 3 | ||
3. ⋮. 255 | 103h. ⋮. 1FFh | 3. ⋮. 255 | 6. ⋮. 32640 | .. Последний 9-битный код | |
256. ⋮. 767 | 200h. ⋮. 3FFh | 10 | 256. ⋮. 767 | 32896. ⋮. 294528 | .. Последний 10-битный код |
768. ⋮. 1791 | 400h. ⋮. 7FFh | 11 | 768. ⋮. 1791 | 295296. ⋮. 1604736 | .. Последний 11-битный код |
1792. ⋮. 3839 | 800h. ⋮. FFFh | 12 | 1792. ⋮. 3839 | 1606528. ⋮. 7370880 | .. Таблица кодов заполнена |
⋮ | FFFh | 3839 | Максимальный код может повторяться для большего количества пикселей одного цвета.. Общее сжатие данных асимптотически приближается к. 3839 × 8/12 = 2559 +1/3 | ||
101h | Конец данных изображения |
Показанные значения кода упакованы в байты, которые затем упаковываются в блоки до 255 байтов. Блок данных изображения начинается с байта, который объявляет количество следующих байтов. Последний блок изображения помечается байтом нулевой длины блока.
Чередование
Спецификация GIF позволяет изображению в пределах логического экрана файла GIF указывать, что оно чередуется; т.е. порядок строк растра в блоке данных не является последовательным. Это позволяет частично отображать изображение, которое можно распознать до того, как будет нарисовано полное изображение.
Изображение с чересстрочной разверткой делится сверху вниз на полосы высотой 8 пикселей, и строки изображения в следующем порядке:
- Шаг 1: строка 0 (самая верхняя строка) из каждой полосы.
- Этап 2: строка 4 из каждой полосы.
- Этап 3: строки 2 и 6 из каждой полосы.
- Этап 4: строки 1, 3, 5 и 7 из каждой полосы.
Пиксели в каждой строке не чередуются, а отображаются последовательно слева направо. Как и в случае с изображениями без чересстрочной развертки, нет разрыва между данными для одной строки и данными для следующей. Индикатор того, что изображение является чересстрочным, устанавливается битом в соответствующем блоке дескриптора изображения.
Анимированный GIF
GIF может использоваться для отображения анимации, как на этом изображении Колыбель Ньютона.
Анимация GIF, состоящая из двух фотографий, одна трансформируется в прочее
Хотя GIF не разрабатывался как среда анимации, его способность хранить несколько изображений в одном файле, естественно, предполагала использование формата для хранения кадров последовательности анимации. Чтобы упростить отображение анимации, спецификация GIF89a добавила расширение управления графикой (GCE), которое позволяет раскрашивать изображения (кадры) в файле с задержкой по времени, образуя видеоклип. Каждый кадр в анимационном GIF представлен своим собственным GCE, определяющим время задержки после рисования кадра. Глобальная информация в начале файла по умолчанию применяется ко всем кадрам. Данные ориентированы на поток, поэтому файловое смещение начала каждого GCE зависит от длины предыдущих данных. В каждом кадре данные изображения с LZW-кодированием расположены в субблоках размером до 255 байтов; размер каждого субблока объявляется байтом, который ему предшествует.
По умолчанию анимация отображает последовательность кадров только один раз, останавливаясь, когда отображается последний кадр. Чтобы включить цикл анимации, Netscape в 1990-х годах включил блок расширения приложения (предназначенный для того, чтобы отключить приложением добавлений информацию о приложении в файле GIF) для реализации блока приложения Netscape (NAB). Этот блок, расположенный непосредственно перед последовательностью кадров анимации, определяет, сколько раз последовательность кадров должна быть воспроизведена (от 1 до 65 535 раз) или что она должна повторяться непрерывно (ноль означает бесконечный цикл). Поддержка этих повторяющихся анимаций появилась в Netscape Navigator версии 2.0, а затем распространилась в других браузерах. Большинство браузеров теперь распознают и NAB, хотя это не является строго спецификацией GIF89a.
В следующем показателе структуры файла анимации Вращающаяся земля (большая).gif, отображаемое (в виде эскиза) в информационном окне статьи.
байт # шестнадцатеричный текст или (шестнадцатеричное) значение 0: 47 49 46 38 39 61 GIF89a Заголовок Логический дескриптор экрана 6: 90 01 400 - ширина в пикселях 8:90 01 400 - высота в пикселях A: F7 - GCT следует для 256 цветов с разрешением 3 x 8 бит / первичный B: 00 0 - цвет фона # 0 C: 00 - соотношение сторон пикселей по умолчанию D: Глобальная таблица цветов : 30D: 21 FF Расширение приложения блок 30F: 0B 11 - одиннадцать байтов данных следуют за 310: 4E 45 54 53 43 41 50 45 NETSCAPE - 8-значное имя приложения 32 2E 30 2.0 - «код аутентификации» приложения 31B: 03 3 - еще три байта данных 31C: 01 1 - индекс текущего субблока данных (всегда 1 для блока NETSCAPE) 31D: FF FF 65535 - беззнаковое число повторов 31F: 00 - конец блока расширения приложения 320: 21 F9 Расширение графического управления для кадра №1 322: 04 4 - байта в текущем блоке 323: 04 000..... - зарезервировано; 5 младших битов - это битовое поле... 001.. - метод удаления 1: не удалять...... 0. - нет ввода пользователя....... 0 - прозрачный цвет не задан 324: 09 00 - задержка 0,09 сек перед рисованием следующего кадра 326: FF - индекс прозрачного цвета 327: 00 - конец GCE блок 328: 2C Дескриптор изображения кадра №1 329: 00 00 00 00 (0,0) - NW угол кадра в 0, 0 32D: 90 01 90 01 (400,400) - Ширина и высота кадра: 400 × 400 331: 00 - нет приложения таблицы цветов; без чередования 332: 08 8 Минимальный размер кода LZW; Данные изображения начала кадра # 1 333: FF 255 - 255 байтов изображения данных в кодировке LZW следуют за 334: данные 433: FF 255 - 255 байтов данных изображения в кодировке LZW следуют за данными: 92C0: 00 - конец Данные LZW для этого кадра 92C1: 21 Расширение графического управления F9 для кадра # 2 :: EDABD: 21 Расширение графического управления F9 для кадра # 44: F48F5: 3B Знак конца файла
Задержка анимации для каждого кадра указывается в GCE в сотые доли секунды. Некоторая экономия данных возможна, когда для кадра требуется только перезапись части пикселей дисплея. Браузеры или другие дисплеи, не поддерживающие анимированные GIF-файлы, обычно показывают только первый кадр.
Размер и качество цвета анимированных файлов GIF может значительно различаться в зависимости от приложения, которое использовалось для их создания. Стратегии минимизации размера файла включают использование общей таблицы цветов для каждого кадра цветов (не полные таблицы цветов для каждого кадра цветов) и минимизацию количества пикселей, охватываемых последовательными последовательностями пикселей (так, чтобы только те пиксели, которые меняются от одного кадра к следующему в последнем) кадре). Простая упаковка кадровых изображений в составную анимацию приводит к большим размерам файлов.
Internet Explorer замедляет GIF-файлы, если частота кадров составляет 20 кадров в секунду или выше, а Microsoft сообщает, что Google Chrome и Safari также замедляют некоторые анимации GIF.
С начала 1995 года Университет Ульма использовал анимированный GIF в качестве формата потокового видео в реальном времени для демонстрации управляемой модели железной дороги.
Метаданные
Метаданные могут храниться в файлах GIF в виде блока комментариев, блока обычного текста или блока расширения приложения для конкретного приложения. Некоторые графические редакторы используют неофициальные блоки расширений приложений для включения данных, используемых для создания изображения, чтобы его было восстановить для дальнейшего редактирования.
Все эти методы технически требуют, чтобы метаданные были разбиты на подблоки, чтобы приложения перемещались по блоку метаданных, не зная его внутренние структуры.
Стандарт метаданных Extensible Metadata Platform (XMP) представил неофициальный, но широко распространенный блок расширения приложения «Данные XMP» для включения данных XMP в файлы GIF. Данные данные XMP кодируются с использованием UTF-8 без символов NUL, в данных нет 0 байтов. Вместо того, чтобы разбивать данные на формальные субблоки, блок расширения завершается «волшебным трейлером», который направляет любое приложение, обрабатывающее данные как субблоки, к финальному байту 0, который завершает цепочку субблоков.
Защита патентов Unisys и LZW
В 1977 и 1978 годах Джейкоб Зив и Абрахам Лемпель опубликованные пару статей о новом классе без потерь алгоритмы сжатия данных, теперь все вместе называемые LZ77 и LZ78. В 1983 году Терри Велч разработал быстрый вариант LZ78, который получил название Lempel–Ziv–Welch (LZW).
Уэлч подал заявку на патент на метод LZW в июне 1983 года. Полученный в результате патент, US 4558302, выданный в декабре 1985 года, был передан Sperry Corporat ion, который имел объединилась с Burroughs Corporation в 1986 году и образовала Unisys. Дополнительные патенты были получены в Великобритании, Франции, Германии, Италии, Японии и Канаде.
В дополнение к вышеуказанным патентам патент Уэлча 1983 года также включает ссылки на несколько других патентов, которые повлияли на него, включая дваских патента 1980 года (JP9343880A и JP17790880A ) от Джун Канатсу из NEC, США Патент 4021782 (1974) от Джона С. Хёрнинга, США. Патент 4366551 (1977) Клауса Э. Хольца и голландский патент 1981 года (DE19813118676 ) Карла Экхарта Хайнца.
В июне 1984 года статья Уэлча была опубликована в журнале IEEE, впервые публично описанный технику LZW. LZW стал популярным методом сжатия данных. Unisys заключила лицензионные соглашения с более чем сотней компаний.
Популярность LZW заставила CompuServe выбрать его для сжатия технология для своей версии GIF, разработанная в 1987 году. В то время CompuServe не знала о патенте. Unisys стало известно, что в версии GIF использовался метод сжатия LZW, после сентября 1993 года они вступили в переговоры о лицензировании с CompuServe. О последующем соглашении было объявлено 24 декабря 1994 года. Unisys заявила, что ожидает, что все крупные коммерческие компании, предоставляющие информационные услуги в Интернете, будут использовать эту технологию. Патент LZW на лицензирование технологий от Unisys по разумной цене, но не требует лицензирования или уплаты сборов для некоммерческих приложений на основе GIF, в том числе для использования в онлайн-сервисах.
После этого объявления CompuServe и Unisys подверглись массовому осуждению, и многие разработчики программного обеспечения пригрозили прекратить использование GIF. Формат PNG (см. Ниже) был разработан в 1995 году как предполагаемая замена. Однако получение поддержки со стороны производителей веб-браузеров и другого программного обеспечения для формата PNG оказалось трудным, и заменить GIF было невозможно, хотя популярность PNG постепенно возрастала. Поэтому были разработаны варианты GIF без сжатия LZW. Например, библиотека libungif, основанная на giflib Эрика С. Раймонда, позволяет создавать файлы GIF в соответствующих форматах данных, но без использования функций сжатия, что позволяет избежать использования патента Unisys LZW. А 2001 Др. В статье Добба описана другая альтернатива сжатию LZW, основанная на квадратных корнях.
В августе 1999 года Unisys изменила детали своей практики лицензирования, объявив о возможности для владельцев некоммерческих и частных веб-сайтов получить лицензию, уплатив единовременный лицензионный сбор в размере 5000 долларов США или 7500 долларов США. Такие лицензии не требуются для владельцев веб-сайтов или других пользователей GIF, которые используют лицензионное программное обеспечение для создания файлов GIF. Тем не менее, Unisys подверглась тысячам онлайн-атак и оскорбительных писем от пользователей, которые считали, что они предъявлены обвинения в размере 5000 долларов или предъявлены иски за использование GIF-файлов на своих сайтах. Несмотря на предоставление лицензий сотням некоммерческих организаций, школ и правительств, Unisys была полностью неспособна создать какую-либо хорошую рекламу и продолжала подвергаться осуждению со стороны отдельных лиц и организаций, таких как Лига за свободу программирования, которая начала Кампания «Сжечь все гифки» в 1999 году.
Срок действия патента на LZW в пределах Штатах истек 20 июня 2003 года. Срок действия соответствующих патентов в Соединенном Королевстве, Франции, Германии и Италии истек 18 июня 2004 года, срок действия японских патентов истек 20 июня 2003 года. 20 июня 2004 г., а срок действия канадского патента истек 7 июля 2004 г. Следовательно, Unisys имеет другие патенты и заявки на патенты, касающиеся усовершенствований технологии LZW, теперь можно свободно использовать GIF.
Альтернативы
PNG
Portable Network Graphics (PNG) был разработан как замена GIF, чтобы избежать нарушения патента Unisys на метод сжатия LZW. PNG предлагает напряжение и больше возможностей, чем GIF, за исключением анимации. PNG более подходит, чем GIF, в тех случаях, когда требуются истинных цветов и альфа-прозрачность.
Хотя поддержка формата PNG появилась медленно, веб-браузеры обычно PNG. Предыдущие версии Internet Explorer не все функции PNG. Версии 6 и более ранние нефа аль-канал прозрачность без использования специфичных для Microsoft HTML-расширений. Гамма коррекция изображений PNG не поддерживалась до версии 8, а отображение этих изображений в более ранней версиих версии может иметь неправильный оттенок.
Для идентичных 8-битных (или ниже) данных изображения файлы PNG обычно меньше, чем эквивалентные GIF, из-за более эффективных методов сжатия, используемых при кодировании PNG. Полная поддержка GIF затруднена в основном из-за сложной структуры холста, которую он позволяет, хотя это то, что обеспечивает функции компактной анимации.
Форматы анимации
Видео решают многие проблемы, которые используются в файлах GIF при обычном использовании в Интернете. Они включают в себя значительно меньшие размеры файлов , возможность обхода ограничения 8-битного цвета, а также улучшенную обработку кадров и сжатие с помощью кодеков . Практически универсальная поддержка формата GIF в веб-браузерах и отсутствие официальной поддержки видео в стандарте HTML привели к тому, что GIF приобрел популярность в целях отображения коротких видеофайлов. в сети.
MNG («Сетевая графика с изображениями») изначально разработан как решение для анимации на основе PNG. MNG достигла версии 1.0 в 2001 году.
В 2006 году расширение формата PNG под названием APNG («Анимированная переносимая сетевая графика») было предложено в качестве альтернативного формата MNG компанией Mozilla. APNG поддерживается большинством браузеров с 2019 года. APNG предоставляет возможность анимировать файлы PNG, сохраняя при этом обратную совместимость в декодерах, которые не могут понять фрагмент анимации (в отличие от MNG). Старые декодеры просто визуализируют первый кадр анимации. Группа PNG официально отклонила APNG как официальное расширение 20 апреля 2007 года. Было несколько предложений по созданию простого формата анимированной графики на основе PNG с различными подходами. Тем не менее, переносимая сетевая графика все еще находится в разработке Mozilla и поддерживается в Firefox 3, в то время как поддержка MNG была прекращена. APNG в настоящее время поддерживает все веб-браузеры, включая Chrome, начиная с версии 59.0, а также Opera, Firefox и Edge.
Встроенные объекты Adobe Flash и MPEG используются на некоторых веб-сайтах для отображения простого видео, но требуют использования дополнительного подключаемого модуля. WebM и WebP существуют в разработке и поддерживаются некоторыми веб-браузерами. Другие варианты веб-анимации включают обслуживание отдельных кадров с использованием AJAX или анимацию изображений SVG с использованием JavaScript или SMIL («язык синхронизированной интеграции мультимедиа «).
С введением повсеместной поддержки тега HTML5 video () в большинстве веб-браузеров некоторые веб-сайты используют зацикленную версию тега видео, сгенерированного JavaScript функции. Яркими примерами являются Gfycat и Imgur и их метаформат GIFV, которые на самом деле являются тегом видео, воспроизводящим зацикленный MP4 или WebM. сжатое видео.
Высокоэффективный формат файла изображения (HEIF) — это формат файла изображения, завершенный в 2015 году, в котором используется дискретное косинусное преобразование (DCT) сжатие с потерями Алгоритм, основанный на видеоформате HEVC и относящийся к формату изображения JPEG. В отличие от JPEG, HEIF поддерживает анимацию. По сравнению с форматом GIF, в котором сокращается DCT, HEIF обеспечивает значительно более эффективное сжатие. HEIF хранит больше информации и создает анимированные изображения более высокого качества при небольшой части эквивалентного размера GIF.
VP9 поддерживает только альфа-композитинг с 4: 2: 0 субдискретизацией цветности в формате пикселей YUV A420, который может не подходить для GIF -файлов, сочетающих прозрачность с растеризованной векторной графикой с мелкими цветовыми деталями.
Использует
В апреле 2014 года 4chan добавила поддержку беззвучных видео WebM размером менее 3 МБ и длиной 2 минуты, а также в октябре 2014 года Imgur начал преобразовывать любые файлы GIF, загруженные на сайт, в видео и придавать ссылку на проигрыватель HTML вид реального файла с расширением .gifv
.
С января 2016 года Telegram начал перекодирование всех GIF-файлов в видео MPEG4, которые «требуют на 95% меньше места на диске для того же качества изображения».
См. Также
- Синемаграф, частично анимированная фотография, часто в формате GIF
- Сравнение форматов графических файлов
- Сравнение механизмов верстки (графика)
- GIF art, форма digital art, связанная с GIF
- GNU plotutils (поддерживает псевдо-GIF, который использует кодировку длины серий вместо LZW)
- Microsoft GIF Animator, историческая программа для создания простых анимированных GIF-файлов
- Патент на программное обеспечение
Ссылки
Внешние ссылки
- Проект GIFLIB
- spec-gif89a.txt Спецификация GIF 89a на w3.org
- спецификация GIF 89a, переформатированная в HTML
- Объяснение LZW и GIF
- Анимированные GIF : шестиминутный документальный фильм, созданный Off Book (веб-серия)
- GifCities (поисковая система анимированных GIF-файлов GeoCities)
А Б В Г Д Е Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Э Ю Я
ГИФ-анима́ция, -и
Рядом по алфавиту:
гита́ны , -ов и -а́н, ед. гита́н, -а (испанские цыгане)
гита́ра , -ы
гитари́ст , -а
гитари́стка , -и, р. мн. -ток
гита́рка , -и, р. мн. -рок
гита́рный
гита́рочка , -и, р. мн. -чек
ги́тик , : нау́ка уме́ет мно́го ги́тик
гитлери́зм , -а
гитлеровец , -вца, тв. -вцем, р. мн. -вцев
ги́тлеровский , (от Ги́тлер)
гитлерю́генд , [ръю́], -а
ги́тов , -а
ги́ттия , -и
ГИФ , -а и нескл., м. (инф.)
ГИФ-анима́ция , -и
ГИФ-фа́йл , -а
ГИФО́ , нескл., с. (сокр.: государственное именное финансовое обязательство)
гифомице́ты , -ов, ед. -це́т, -а
ги́фы , гиф, ед. ги́фа, -ы
ги́чка , -и, р. мн. ги́чек
гишпа́нский , (устар. и шутл. к испа́нский)
ГКО , [гэкао́], нескл., ж. (сокр.: государственная краткосрочная облигация) и с. (сокр.: государственное казначейское обязательство)
глава́ , -ы́, мн. гла́вы, глав, ж. (голова, устар.; купол; раздел текста), м. и ж. (руководитель)
глава́рь , -аря́
главбу́х , -а
главвра́ч , -ача́, тв. -о́м
главе́нство , -а
главе́нствовать , -твую, -твует
главе́нствующий
главк , -а
|
|
Расширение |
|
---|---|
MIME |
|
Сигнатура |
|
Разработан |
CompuServe |
Тип формата |
растровая графика |
GIF (англ. Graphics Interchange Format — рус. формат для обмена изображениями) — популярный формат графических изображений. Способен хранить сжатые данные без потери качества в формате не более 256 цветов. Не зависящий от аппаратного обеспечения формат GIF был разработан в 1987 году (GIF87a) фирмой CompuServe для передачи растровых изображений по сетям. В 1989-м формат был модифицирован (GIF89a), были добавлены поддержка прозрачности и анимации. GIF использует LZW-компрессию, что позволяет неплохо сжимать файлы, в которых много однородных заливок (логотипы, надписи, схемы).
GIF широко используется на страницах интернета.
Содержание
- 1 Произношение названия
- 2 Область применения
- 2.1 Анимированные изображения
- 2.2 Сжатие
- 2.3 Чересстрочный GIF
- 3 История
- 4 Патентная защита
- 5 Альтернатива
- 6 См. также
- 7 Примечания
- 8 Ссылки
Произношение названия
Создатели формата произносили его название как «джиф» /dʒɪf/. Тем не менее, в англоязычном мире широко используется и произношение «гиф» /gɪf/, основанное на том, что GIF — сокращение от Graphics Interchange Format. Оба варианта произношения указаны как правильные словарями Oxford English Dictionary[1] и American Heritage Dictionary.[2]
Область применения
Изображение в формате GIF хранится построчно, поддерживается только формат с индексированной палитрой цветов. Стандарт разрабатывался только для поддержки 256-цветовой палитры.
Один из цветов в палитре может быть объявлен «прозрачным». В этом случае в программах, которые поддерживают прозрачность GIF (например, большинство современных браузеров) сквозь пиксели, окрашенные «прозрачным» цветом будет виден фон. «Полупрозрачность» пикселей (технология альфа-канала) не поддерживается.
Анимированные изображения
Пример простейшей анимации
Анимированные GIF на Викискладе? |
Формат GIF поддерживает анимационные изображения. Они представляют собой последовательность из нескольких статичных кадров, а также информацию о том, сколько времени каждый кадр должен быть показан на экране. Анимацию можно сделать цикличной (англ. loop), тогда вслед за последним кадром начнётся воспроизведение первого кадра и т. д.
Недокументированной, но поддерживаемой возможностью является сохранение большего количества цветов с помощью анимированного GIF с нулевой задержкой между кадрами. При этом преодолевается ограничение в 256 цветов: каждый кадр содержит свою палитру.[уточнить]
Сжатие
GIF использует формат сжатия LZW. Таким образом, хорошо сжимаются изображения, строки которых имеют повторяющиеся участки. В особенности изображения, в которых много пикселей одного цвета по горизонтали.[3]
Алгоритм сжатия LZW относится к форматам сжатия без потерь. Это означает, что восстановленные из GIF данные будут в точности соответствовать упакованным. Следует отметить, что это верно только для 8-битных изображений с палитрой, для цветной фотографии потери будут обусловлены переводом её к 256 цветам.
Метод сжатия LZW разработан в 1978 году израильтянами Абрахамом Лемпелем и Якобом Зивом, а позднее доработан в США Терри Велчем. LZW сжимает данные путём поиска одинаковых последовательностей (они называются «фразы») во всем файле. Выявленные последовательности сохраняются в таблице, им присваиваются более короткие маркеры (ключи).
Метод LZW, так же, как и RLE, лучше действует на участках однородных, свободных от шума цветов, он действует гораздо лучше, чем RLE, при сжатии произвольных графических данных, но процесс кодирования и распаковки происходит медленнее.
Чересстрочный GIF
Формат GIF допускает чересстрочное хранение данных. При этом строки разбиваются на группы, и меняется порядок хранения строк в файле. При загрузке изображение проявляется постепенно, в несколько проходов. Благодаря этому, имея только часть файла, можно увидеть изображение целиком, но с меньшим разрешением.
В чересстрочном GIF’е сначала записываются строки 1, 9, 17 и т. д. Таким образом, загрузив 1/8 данных, пользователь будет иметь представление о целом изображении. Вторым проходом следуют строки 5, 13, 21, разрешение изображения в браузере ещё вдвое увеличивается. Наконец, третий и четвёртый проход передают (3, 7, 11, 15, 19…) и (2, 4, 6, 8, …). Таким образом, задолго до окончания загрузки файла пользователь может понять, что внутри и решить, стоит ли ждать полной загрузки изображения. Чересстрочная запись незначительно увеличивает размер файла, но это, как правило, оправдывается приобретаемым свойством.
История
Существует две спецификации формата GIF — GIF 87a и GIF 89a.
Первая спецификация была создана в 1987 году компанией CompuServe для замены устаревшего формата RLE. GIF стал популярен в ходе развития интернета, так как позволял использовать более компактные (по размеру файла) по сравнению с другими форматами картинки на веб-страницах. Хотя к настоящему времени формат во многом устарел, и для его замены создан формат PNG, он по прежнему широко используется. GIF-формат востребован при создании так называемых синемаграфов.
Патентная защита
GIF первоначально был проприетарным форматом, однако срок его патентной защиты истёк. В США патент на алгоритм сжатия LZW, использующийся в GIF (патент № 4 558 302) истёк 20 июня 2003 года. Срок действия канадского патента завершился 7 июля 2004 года. Действие патента для Великобритании, Франции, Германии и Италии завершилось 18 июня 2004 года, а для Японии — 20 июня 2004 года.
Срок действия последнего патента на GIF истёк 11 августа 2006 года.
Альтернатива
Существует формат APNG, созданный в 2004 году, использующий 24-битные цвета и 8-битную полупрозрачность, работающий в браузерах Mozilla Firefox и Opera начиная с 2007 года. Некоторые программы и расширения также поддерживают APNG.
См. также
- PNG | MNG | APNG | JPEG
Примечания
- ↑ Oxford English Dictionary. Oxford University Press. Архивировано из первоисточника 22 августа 2011. Проверено 15 апреля 2007.
- ↑ American Heritage Dictionary. Houghton-Mifflin. Архивировано из первоисточника 22 августа 2011. Проверено 15 апреля 2007.
- ↑ § 8. Простой секрет ГИФа
Ссылки
- The Graphics File Format Page (англ.)
- Спецификация формата GIF87a (рус.)
|
|
---|---|
Видео/аудио |
3GP • ASF • AVI • Bink • DMF • DPX • EVO • FLV • Matroska (MKV) • WebM • MPEG-PS • MPEG-TS • MP4 • MXF • NUT • Ogg • Ogg Media • QuickTime • RealMedia • Smacker • RIFF • VOB • сравнение • сжатие |
Аудио |
AIFF • APE • AU • DSD • DXD • MLP • MP3 • FLAC • SHN (англ.) WAV • WMA • сравнение • сжатие |
Графические форматы (сжатие) | |
Растровые |
Без потерь: BMP • FPX • GIF • ICO • ILBM • JBIG • PCX • PNG • PNM • PSD • RAW • TGA • WBMP • XCF • Включая сжатие с потерями: EXR • ICER • JBIG2 • JPEG / JP2 / JPEG-LS • JPEG XR (HD Photo) • PGF (англ.) • TIFF • WebP • Анимационные: APNG • GIF • MNG |
Векторные |
AI • CDR • EMF • EPS • PS • SVG • WMF • XPS • Анимационные: SVG • SWF • 3D: 3DS • VRML • X3D |
Комплексные |
CGM • DjVu • PDF |
Графическому формату GIF в прошлом году стукнуло 25 лет, но он все ещё пользуется огромной популярностью в интернете. Анимированные GIF’ы сейчас переживают вторую молодость: даже Google недавно запустил специальный фильтр по такому типу файлов.
Неудивительно, что позавчера на церемонии Webby Awards особую награду за «пожизненные достижения» присудили автору стандарта GIF Стиву Уилхайту (Steve Wilhite). Его фото справа — из журнала “Online Today” за октябрь 1987 года, где вышла статья о новом формате графики.
«GIF оказался невероятно живучей технологией, — говорит Дэвид-Мишел Дэвис, исполнительный директор Webby Awards, — Даже с распространением широкополосного доступа».
В далёком 1987 году сложно было представить, что GIF станет использоваться в первую очередь для анимации и коротких видеороликов и даже спустя четверть века не придумают ничего лучше. В то время просто хотели создать единый формат для веба, чтобы картинки одинаково отображались на всех компьютерных платформах. Это было серьёзной проблемой.
Стив Уилхайт работал в компании CompuServe — первом в США массовом интернет-провайдере. Компания хотела предоставлять своим пользователям графические сервисы через веб, например, показывать цветную карту погоды. Мистер Уилхайт увлекался технологиями сжатия, так что решил помочь. Он представлял себе, каким должен быть формат, и через месяц выкатил вариант под названием GIF (Graphics Interchange Format), это был июнь 1987 года.
Новинка мгновенно стал популярной. Некоторые специалисты прекратили работу над чёрно-белыми форматами графики, все перешли на GIF. В стандарте Стив Уилхайт даже предусмотрел возможность анимации с временем показа одного кадра от 0,01 c до 655 с.
В своей жизни Стив Уилхайт не сделал ни одного анимированного GIF’а, но назвал любимым произведением танцующего ребёнка из 1996 года.
Сейчас Стив Уилхайт отошёл от дел, вышел на пенсию, построил дом за городом, увлекается фотографией и Java-программированием. Он гордится своим детищем — форматом GIF — но его жутко раздражает, что до сих пор продолжаются споры о правильном произношении. «Оксфордский словарь английского языка признаёт оба произношения, — говорит мистер Уилхайт. — Они ошибаются. Это мягкое «джи», произносится как «джиф» (jif). Нечего здесь обсуждать».
Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.
Как вы привыкли произносить GIF?
Проголосовали 5218 пользователей.
Воздержались 195 пользователей.