Question

In GIMP, you're able to save an image as a C header file. I did so with an XPM file, which looks like the image below:

If I were to save the XPM image as a C header file, GIMP will output this C header file.

In order to process each pixel of the given image data, the header pixel is called repeatedly. What I don't understand is what the header pixel does to process the data in the first place.

#define HEADER_PIXEL(data,pixel) {\
pixel[0] = (((data[0] - 33) << 2) | ((data[1] - 33) >> 4)); \
pixel[1] = ((((data[1] - 33) & 0xF) << 4) | ((data[2] - 33) >> 2)); \
pixel[2] = ((((data[2] - 33) & 0x3) << 6) | ((data[3] - 33))); \
data += 4; \
}

When I saw it in use in another person's code, they stated the byte order was in the wrong order and rearranged it themselves. They used it like this:

char *pixel, *data = header_data;
int i = width * height;
*processed_data = pixel = malloc(i * 4 + 1);
while(i-- > 0) {
    pixel[0] = ((((data[2] - 33) & 0x3) << 6) | ((data[3] - 33)));
    pixel[1] = ((((data[1] - 33) & 0xF) << 4) | ((data[2] - 33) >> 2));
    pixel[2] = (((data[0] - 33) << 2) | ((data[1] - 33) >> 4));
    pixel[3] = 0;
    data += 4;
    pixel += 4;
}

But that didn't really help me understand what is going on with all the bit shifting and bitwise or's and "why minus 33?" and so forth. If anyone can give an explanation on what is going on to process to the image data in the header, that would be much appreciated.

Thanks in advance!

Was it helpful?

Solution

Each pixel is represented by 3 bytes. These pixels are defined as a character array, named header_data.

The problem is that not every byte is a printable character that could exist in that header file.

This is solved by only using the printable characters 33 through 97. That gives 6 bits of information, so every four characters will give 24 bits, which can represent all permutations of 3 bytes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top