Dale Rastanixon
Dale Rastanixon

Reputation: 41

Reading data from GIF Headers in C

The first 13 bytes of any GIF image file are as follows:

3 bytes - the ascii characters "GIF"
3 bytes - the version - either "87a" or "89a"
2 bytes - width in pixels
2 bytes - height in pixels
1 byte - packed fields
1 byte - background color index
1 byte - pixel aspect ratio

I can get the first six bytes myself by using some sort of code like:

int G = getchar();
int I = getchar();
int F = getchar();

etc .. doing the same for the 87a/89a part, all this gets the first 6 bytes, providing the ascii characters for, say, GIF87a.

Well, I can't manage to figure out how to get the rest of the information. I try going along with the same getchar(); method, but it's not what I would expect it to be. Say I have a 350x350 GIF file, since the width and height is 2 bytes each, i use getchar 2 times, and I end up with the width being "94" and "1", two numbers, as there's two bytes. But how would I use this information to get the actual, in base 10, width and height? I tried bitwise-anding 94 and 1, but then realized it returns 0.

I figure maybe if I can find out how to get the width and height I'll be able to access the rest of the information on my own.

Pixel width and height are stored in little indian format.

Upvotes: 0

Views: 2093

Answers (2)

Ganesh
Ganesh

Reputation: 5990

Typically for reading a compressed bitstream or image data, we could open the file in read binary mode, read the data and interpret the same through a getBits functionality. For example, please consider a sample below

fptr = fopen("myfile.gif", "rb");

// Read a word
fread(&cache, sizeof(unsigned char), 4, fptr);

//Read your width through getBits
width = getBits(cache, position, number_of_bits);

Please refer here K & R Question: Need help understanding "getbits()" method in Chapter 2 for more details on getBits

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182819

It's just like any other number broken into parts with a limited range. For example, look at 43. Each digit has a limited range, from 0 to 9. So the next digit is the number of 10's, then hundreds (10*10) and so on. In this case, the values can range from 0 to 255, so the next number is the number of 256's.

256 * 1 + 94 = 350

The standard should specify the byte order, that is, whether the most significant (called big endian) comes first of the least significant (called little endian) comes first.

Byte Order: Little-endian

Upvotes: 3

Related Questions