GIF Transparency in Graphic Control Extension
In the GIF89a specification, transparency is handled per frame using the Graphic Control Extension (GCE), an optional metadata block that precedes an image descriptor. This extension designates transparency through a two-part mechanism: a single-bit flag within a packed byte that activates the feature, followed by a dedicated byte that specifies the exact palette index to be rendered as transparent. This approach allows decoders to treat specific pixels as see-through without altering the underlying RGB values stored in the palette.
The Graphic Control Extension Structure
The Graphic Control Extension consists of an 8-byte block formatted as follows:
- Extension Introducer (1 byte): Always
0x21. - Graphic Control Label (1 byte): Always
0xF9, identifying the block as a Graphic Control Extension. - Block Size (1 byte): Fixed value of
0x04, indicating four bytes of payload data follow. - Packed Fields (1 byte): Bit field containing control flags.
- Delay Time (2 bytes): Frame duration in hundredths of a second.
- Transparent Color Index (1 byte): The target palette index.
- Block Terminator (1 byte): Always
0x00.
The Packed Fields Byte
The Packed Fields byte (Byte 4 of the extension) contains several sub-fields:
- Reserved (Bits 7–5): Three unused bits.
- Disposal Method (Bits 4–2): Determines what happens to the frame after display.
- User Input Flag (Bit 1): Indicates whether user input is expected before continuing.
- Transparent Color Flag (Bit 0): The least significant bit.
To enable transparency, Bit 0 must be set to 1. If this
bit is set to 0, transparency is disabled for that graphic,
and the decoder ignores the value in the Transparent Color Index byte
entirely.
The Transparent Color Index Byte
When the Transparent Color Flag is set to 1, the decoder
evaluates Byte 7 of the extension, designated as the Transparent
Color Index.
This byte stores an unsigned 8-bit integer (ranging from 0 to 255) pointing directly to a specific slot in the active color table. The active table is the Local Color Table for the immediately following image descriptor if present; otherwise, it is the Global Color Table defined in the GIF header.
Rendering Behavior
During decompression, the raster data consists of a stream of index values referencing the color palette. When the decoder processes a pixel:
- If the pixel's palette index matches the Transparent Color Index (and the Transparent Color Flag is active), the decoder does not draw that pixel to the canvas, leaving the underlying background or previous frame visible.
- If the index does not match, the decoder maps the index to the corresponding RGB triplet in the active color table and renders the pixel as opaque.
GIF transparency is strictly binary (1-bit alpha); a pixel is either completely opaque or completely transparent, with no support for semi-transparency or alpha blending.