I am learning the physics engine Chipmunk. In the source code, the example demo "LogoSmash" uses char
array to store image_data
, but I don't understand how to do that, it's amazing!
Here is the LogoSmash code in question:
static const unsigned char image_bitmap[] = {
15, -16, 0, 0, ...
}
Will someone explain how this works and how I could do this?
Answer
In C++, a char
is an integral data type. It holds numbers, and on most implementations you are likely to encounter, it will be capable of holding 8 bits of data.
The 24-bit RGB color representation (the most common one that does not encode transparency information) uses 8 bits for each red, blue and green channel. Thus, a single char
can hold a single color channel of data, and three char
objects can hold a complete RGB pixel. If you include transparency via an alpha channel (RGBA), four char
objects can completely define a pixel.
Thus, an array of 4 x width x height
char
objects can hold the pixel information for a image of width
by height
pixels. Note that one usually uses unsigned char
s in practice, since signed char
s allow negative values which is generally semantic nonsense for color values.
Since char
s are just numbers, it's perfectly possible to encode the image data directly into one's source code as follows:
unsigned char image[] = {
255, 0, 0, 0, // 1st RGBA pixel, completely red.
0, 255, 0, 0, // 2nd RGBA pixel, completely blue.
// and so on
};
It's rather impractical for images of any kind of complexity, since it both requires you to write or find some tool that will save or convert bitmaps into source code, and it requires a re-compile to change any part of the image (which is not very good for iteration), but it's a common technique for really simple demos that don't want to confuse the issue being demonstrated with lots of file IO and image read code and whatnot.
However, I wouldn't recommend using this technique in production code (or really, at all, just load the image from a file, there are plenty of libraries to help you with that).
No comments:
Post a Comment