Go to index page.

The GIFLIB Library

Gershon Elber, May 1991
Eric S. Raymond, Sep 1992
The Graphics Interchange Format(c) is the Copyright property of CompuServe Incorporated. GIF(sm) is a Service Mark property of CompuServe Incorporated.

Gershon wrote: "This library was written because I couldn't find anything similar and I wanted one. I was inspired by the RLE Utah tool kit, which I hoped to port to an IBM PC, but found it to be too machine specific, and its compression ratio too low. I compromised on the GIF format, but I am not sure how long 8 bits per pixel will be enough."

This document explains the GIF library code in directory `lib'. The code is collected into libgif.a which is used in all the utilities in `util'. It can be used in any application needs to read/write the GIF file format. This document does not explain the GIF file format and assumes you know it, at least to the level of the GIF file structure.

When a GIF file is opened, a GIF file descriptor is created which is a pointer to GifFileType structure as follows:


typedef struct GifFileType {
    int SWidth, SHeight,			       /* Screen dimensions. */
	SColorResolution, 		 /* How many colors can we generate? */
	SBackGroundColor;		/* I hope you understand this one... */
    ColorMapObject *SColorMap;			      /* NULL if not exists. */
    int ImageCount;				  /* Number of current image */
    GifImageDesc Image;			   /* Block describing current image */
    struct SavedImage *SavedImages;	/* Use this to accumulate file state */
    VoidPtr Private;	  /* The regular user should not mess with this one! */
} GifFileType;
This structure was copied from gif_lib.h - the header file for the GIF library. Any application program that uses the libgif.a library should include it. Members beginning with S refer to GIF Screen; others hold properties of the current image (a GIF file may have more than one image) or point to allocated store used by various routines.

The user almost never writes into this structure (exception: it may occasionally useful to alter things in the SavedImages array), but can read any of these items at any time it is valid (image information is invalid until first image was read/write).

As the library needs to keep its own internal data, a Private pointer to hidden data is included. Applications should ignore this item.

The library has no static data. This means that it is fully reentrant and any number of GIF files (up to memory limits) can be opened for read/write. Instead of the static data, internal structure pointed by the Private pointer is used.

The library allocates its own memory dynamically, on opening of files, and releases that once closed. The user is never required to allocate any memory for any of the functions of this library nor to free them directly.

In order to reduce disk access, the file buffer is increased to FILE_BUFFER_SIZE (defined in gif_lib.h). The library was compiled in large model on the PC as the memory allocated per file is quite big: about 17k for decoding (DGIF_LIB.C), and 32k for encoding (EGIF_LIB.C), excluding the FILE_BUFFER_SIZE.

Here is a module summary:

egif_lib.c
Encoding routines, all prefixed with E.

dgif_lib.c
Decoding routines, all prefixed with D.

dev2gif.c
Routines to convert specific device buffers into GIF files.

gifalloc.c
Routines for colormap handling and GIF record allocation.

gif_font.c
The 8x8 font table for the GIF utility font.

gif_err.c
Error handler for the library.

The library includes a sixth file of hash-function code which is accessed internally only.

Most of the routines return GIF_ERROR (see gif_lib.h) if something went wrong, GIF_OK otherwise. After an error return, the code in the gif_err.c module can be used to do something about it.

In addition, a module to parse command line arguments is supplied. This module is called getarg.c and its headers are in getarg.h. See the header of getarg.c for details on its usage.

Decoding (dgif_lib.c)

The following functions are used to set up input from a GIF:


GifFileType *DGifOpenFileName(char *GifFileName)
Open a new GIF file using the given GifFileName, and read its Screen information. If any error occurs, NULL is returned and the error handler can be used to get the exact error (see gif_err.c). The file is opened in binary mode, and its buffer size is set to FILE_BUFFER_SIZE bytes.

GifFileType *DGifOpenFileHandle(int GifFileHandle)
Open a new GIF file using the given GifFileHandle, and read its Screen information.

If any error occurs, NULL is returned and the error handler can be used to get the exact error (see gif_err.c).

The file is opened in binary mode, and its buffer size is set to FILE_BUFFER_SIZE bytes.

Once you have acquired a handle on a GIF, there are two ways to read it in. The high-level function


int DGifSlurp(GifFileType)
reads the rest of a complete (possibly multi-image) GIF file from the indicated file handle into in-core allocated structures. It returns GIF_OK on success, GIF_ERROR on failure.

Once you have done this, all image, raster, and extension-block data in the GIF is accessable in the SavedImages member (see the structures in fif_lib.h). When you have modified the image to taste, write it out with EGifSpew().

If you are handling large images on a memory-limited machine, you may need to use the following functions for sequential read.


int DGifGetScreenDesc(GifFileType *GifFile)
Reads the screen information into the GifFile structure. Note this routine is automatically called once a file is opened, and therefore usually need not be called explicitly.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetRecordType(GifFileType *GifFile, GifRecordType *GifType)
As the GIF file can have different records in arbitrary order, this routine should be called once the file was open to detect the next record type, and act upon it. It can return these types in GifType:

1. UndefinedRecordType
something is wrong!

2. ScreenDescRecordType
screen information. As the screen info is automatically read in when the file is open, this should not happen.

3. ImageDescRecordType
next record is an image descriptor.

4. ExtensionRecordType
next record is extension block.

5. TerminateRecordType
last record reached, can close the file.

The first two types can usually be ignored. The function returns GIF_ERROR if something went wrong, GIF_OK otherwise.

int DGifGetImageDesc(GifFileType *GifFile)
Reads image information into the GifFile structure. Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetLine(GifFileType *GifFile, PixelType *GifLine, int GifLineLen)
Load a block of pixels from the GIF file. The line can be of any length. More than that, this routine may be interleaved with DGifGetPixel until all pixels have been read.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetPixel(GifFileType *GifFile, PixelType GifPixel)
Loads one pixel from the GIF file. This routine may be interleaved with DGifGetLine, until all pixels are read. Because of the overhead per each call, use of this routine is not recommended.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetComment(GifFileType *GifFile, char *GifComment)
Load a comment from the GIF file. Because DGifGetRecordType will only tell if the record is of type extension, this routine should be called iff it is known %100 that is must be a comment.

For the definition of a comment, see EGifPutComment. Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetExtension(
        GifFileType *GifFile,
        int *GifExtCode,
        ByteType **GifExtension)
Loads an extension block from the GIF file. Extension blocks are optional in GIF files. This routine should be followed by DGifGetExtensionNext.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetExtensionNext(GifFileType *GifFile, ByteType **GifExtension)
 
As extensions may contain more than one block, use this routine to continue after DGifGetExtension, until *GifExtension is NULL.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetCode(
        GifFileType *GifFile, 
        int *GifCodeSize, ByteType **GifCodeBlock)
It sometimes may be desired to read the compressed code as is without decoding it. This routine does exactly that (with DGifGetCodeNext), and can be used instead of DGifGetLine.

This compressed code information can be written out using the EGifPutCode/EGifPutCodeNext sequence (see gifpos.c for example). Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifGetCodeNext(GifFileType *GifFile, ByteType **GifCodeBlock)
See DGifGetCode above.


int DGifGetLZCodes(GifFileType *GifFile, int *GifCode)
This routine can be called instead of DGifGetLine/DGifGetPixel or DGifGetCode/DGifGetCodeNext to get the 12 bits LZ codes of the images. It will be used mainly for debugging purposes (see GifText.c for example).

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int DGifCloseFile(GifFileType *GifFile)
Close GIF file and free all memory allocated for it. GifFile should not be used after this routine has been called.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.

Encoding (egif_lib.c)

There are two ways to write out a GIF. The high-level function

int EGifSpew(GifFileType *GifFile, int GifFileHandle)
Writes a complete (possibly multi-image) GIF file to the indicated file handle from in-core allocated structures created by a previous DGifSlurp() or equivalent operations. Its arguments are a GIF file descriptor (as above) and an ordinary output file descriptor.

The file is written with a GIF87 stamp unless it contains one of the four special extension blocks defined in GIF89, in which case it is written with a GIF89 stamp.

If you are handling large images on a memory-limited machine, you may need to use the following functions for sequential write.


GifFileType *EGifOpenFileName(char *GifFileName, int GifTestExistance)
Open a new GIF file using the given GifFileName. If GifTestExistance is TRUE, and file exists, the file is not destroyed, and NULL returned.

If any error occurs, NULL is returned and the error handler can be used to get the exact error (see gif_err.c).

The file is opened in binary mode, and its buffer size is set to FILE_BUFFER_SIZE bytes.


GifFileType *EGifOpenFileHandle(int GifFileHandle)
Open a new GIF file using the given GifFileHandle.

If any error occurs, NULL is returned and the error handler can be used to get the exact error (see gif_err.c).

The file is opened in binary mode, and its buffer size is set to FILE_BUFFER_SIZE bytes.


void EGifSetGifVersion(char *Version)
Sets the GIF version of all files opened, until another call to this routine is made. Version is a 3 characters string of the form "87a" or "89a". No test is made to validate this string.


int EGifPutScreenDesc(GifFileType *GifFile,
        int GifWidth, int GifHeight,
        int GifColorRes, int GifBackGround,
        ColorMapObject *GifColorMap)
Update the GifFile Screen parameters, in GifFile structure and in the real file. If error occurs, returns GIF_ERROR (see gif_lib.h), otherwise GIF_OK.

This routine should be called immediately after the GIF file was opened.


int EGifPutImageDesc(GifFileType *GifFile,
        int GifLeft, int GifTop,
        int Width, int GifHeight,
        int GifInterlace,
        ColorMapObject *GifColorMap)
Update GifFile Image parameters, in GifFile structure and in the real file. if error occurs returns GIF_ERROR (see gif_lib.h), otherwise GIF_OK.

This routine should be called each time a new image must be dumped to the file.


int EGifPutLine(GifFileType *GifFile, PixelType *GifLine, int GifLineLen)
 
Dumps a block of pixels out to the GIF file. The slab can be of any length. More than that, this routine may be interleaved with , until all pixels have been sent.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int EGifPutPixel(GifFileType *GifFile, PixelType GifPixel)
Dumps one pixel to the GIF file. This routine may be interleaved with EGifPutLine, until all pixels were sent. Because of the overhead for each call, use of this routine is not recommended.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int EGifPutComment(GifFileType *GifFile, char *GifComment)
Uses extension GIF records to save a string as a comment is the file. The extension code is 'C' (for Comment).

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int EGifPutExtension(
        GifFileType *GifFile,
        int GifExtCode,
        int GifExtLen,
        void *GifExtension)
Dumps the given extension block into the GIF file. Extension blocks are optional in GIF file. Extension blocks of more than 255 bytes or more than one block are not supported.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int EGifPutCode(
        GifFileType *GifFile,
        int *GifCodeSize,
        ByteType **GifCodeBlock)
It sometimes may be desired to write the compressed code as is without decoding it. For example a filter for a GIF file that change only screen size (GifPos), does not need the exact pixel values. Piping out the compressed image as is makes this process much faster.

This routine does exactly that (with EGifPutCodeNext), and can be used instead of EGifPutLine. You'll usually use this with the DGifGetCode/DgifGetCodeNext routines, which reads the compressed code, while EGifPutCode/EGifPutCodeNext write it out. See gifpos.c for example.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.


int EGifPutCodeNext(GifFileType *GifFile, ByteType **GifCodeBlock)
See EGifPutCode above.


int EGifCloseFile(GifFileType *GifFile)
Close a GIF file and free all memory allocated for it. gif-file$ should not be used, once this routine was called.

Returns GIF_ERROR if something went wrong, GIF_OK otherwise.

Color map handling and allocation routines


ColorMapObject *MakeMapObject(int ColorCount, GifColorType *ColorMap)
Allocate storage for a color map object with the given number of RGB triplet slots. If the second argument is non-NULL, initialize the color table portion of the new map from it. Returns NULL if memory is exhausted or if the size is not a power of 2 <= 256.


void FreeMapObject(ColorMapObject *Object)
Free the storage occupied by a ColorMapObject that is no longer needed.


ColorMapObject *UnionColorMap(
        ColorMapObject *ColorIn1, ColorMapObject *ColorIn2,
        GifPixelType ColorTransIn2[])
Create the union of two given color maps and return it. If the result won't fit into 256 colors, NULL is returned, the allocated union otherwise. ColorIn1 is copied as it to ColorUnion, while colors from ColorIn2 are copied iff they didn't exist before. ColorTransIn2 maps the old ColorIn2 into ColorUnion color map table.


SavedImage *GifAttachImage(GifFileType *GifFile)
Add an image block to the SavedImages array. The image block is initially zeroed out. This image block will be seen by any following EGifSpew() calls.

The GIF Utility Font

The 8x8 utility font used in text2gif and gifcolor lives in the library module gif_font.c, in a table called AsciiTable. The library header file includes suitable externs and defines.

The GIF utility font support includes entry points for drawing legends on in-core images, drawing boxes and rectangles, and boxing text. These entry points are as follows:


void DrawText(
        SavedImage *Image,
        const int x, const int y,
        const char *legend,
        const int color)
Draw text using the 8x8 utility font on the saved image. Upper left corner of the text is at image pixel (x, y). Use the specified color index.


void DrawBox(SavedImage *Image,
        const int x, const int y,
        const int w, const int h,
        const int color)
Draw a box on the saved image. Upper left corner of the box is at image pixels (x, y), width is w, height is h. Use the specified color index.


void DrawRectangle(SavedImage *Image,
        const int x, const int y,
        const int w, const int h,
        const int color)
Draw a (filled) rectangle on the saved image. Upper left corner of the box is at image pixels (x, y), width is w, height is h. Use the specified color index.


void DrawBoxedText(SavedImage *Image,
        const int x, const int y,
        const char *legend,
        const int border,
        const int bg, const int fg)
Draw text on a filled rectangle. The rectangle will be sized to fit the text, with upper left hand corner at (x, y) on the saved image. The `border' argument specifies a pixel margin around the text. The `bg' argument is the color table index to fill the rectangle with; `fg' is the color table index to draw the text with.

This function interprets some characters in the legend string specially. A tab (\t) is interpreted as a command to center the following text in the box. A carriage return (\r) is interpreted as a request for a line break.

Error Handling (egif_lib.c)


void PrintGifError(void)
Print a one-line diagnostic on the last giflib error to stderr.


int GifLastError(void)
Return the number of the last giflib error, and clear the error. The error types are defined in gif_lib.h.

Note it is the user's responsibility to call the file closing routine, so the file will be closed (if was opened), and allocated memory will be released.

Device Specific (XXX2gif.c)


int DumpScreen2Gif(char *FileName, int ReqGraphDriver, int ReqGraphMode1,
						       int ReqGraphMode2)
Dumps the whole device buffer as specified by GraphDriver and GraphMode (as defined in TC 2.0 graphics.h) into FileName as GIF file. Current devices supported:

	1. Hercules.

	2. EGA, EGA64, EGAMONO (all modes - see TC graphics.h).

	3. VGA (all modes - see TC graphics.h).

	4. SVGA_SPECIAL. This mode is special and not supported by Borland
	   graphics.h. ReqGraphDriver must be equal to 999, and ReqGraphMode
	   is ignored. This modes assumes 800 by 600 in 16 colors.
	  Returns GIF_ERROR if something went wrong, GIF_OK otherwise.

	5. SGI 4D using gl graphic library - window dump.

	6. X11 window dump.

Command Line Parsing


int GAGetArgs(int argc, char **argv, char *CtrlStr, ...)
Main routine of this module. Given argc & argv as received by the main procedure, the command line CtrlStr, and the addresses of all parameters, parse the command line, and update the parameters.

The CtrlStr defines what types of variables should follow. Look at the beginning of getarg.c for exact usage.

Returns 0 if successful, error number (as defined by getarg.h) otherwise.


void GAPrintErrMsg(int Error)
If an error occurred in GAGetARgs, this routine may be used to print one line diagnostic to stderr.


void GAPrintHowTo(char *CtrlStr)
Given the same CtrlStr as for GAGetArgs, can be used to print a one line 'how to use'.

Skeletons of GIF filters

If you are developing on a virtual-memory OS such as most flavors of UNIX, or are otherwise sure of having enough memory to keep all of GIFs you need to operate in core, writing a filter is trivial. See the file gifspnge.c in util.

A sequential filter skeleton will usually look like the example file giffiltr.c in util.

Please look at the utilities in the util directory for more ideas once you feel comfortable with these skeletons. Also try to follow the coding standards of this package if you want the maintainer to officially add your new utility to it.


Eric S. Raymond <esr@snark.thyrsus.com>