Decoding the width and height of a GIF file

http://www.64Lines.com »» Decoding the width and height of a GIF file «

Overview

The width and height of a GIF image might seem irrelevant to the usual programmer, but when it is required many programmers might not realize how easy it is to decode.Unlike the height and width of a JPEG file, the height of the gif is extremely easy to decode from its header. There is a manual conversion from 2 bytes to a short in this code to make it compatible for any processor and platform - a problem I acutally run into with some code while doing programming for both 68K and x86 CPUs.

Source Code

Decoding Function C++ source code in 9 lines//Gets the GIF size from the array of data passed to the function
static char get_gif_size(unsigned char* data, unsigned int data_size, unsigned short *width, unsigned short *height) {
   //Check for valid GIF file (min 10 bytes for header and size, and the GIF signature)
   if(data_size >= 10 && (data[0] == 'G' && data[1] == 'I' && data[2] == 'F')) {
               *height = data[7]*256 + data[6];
               *width = data[9]*256 + data[8];
               return true;
   } return false;                     //Not a valid GIF file
}

Change Log

References

Gif File Format Specification - a very detailed specification of the gif file format, can be used for a full decoder

Check out the other 64Lines.com articles, tutorials, and tools

All article content is copyright of Michael Petrov, 2012©.
The source code presented in the articles is distributed as freeware, please feel free to use it in your own projects - both commercial and non commercial.
Valid HTML 4.01 TransitionalValid CSS!