cpngbitmaptransparencygif

How to represent binary transparency?


Lately I've been interested in representing uncompressed bitmaps in memory. However, one thing I'm not sure how to implement properly is binary transparency. E.g., I start out with something like this:

struct RGBPixel {
 uint8_t red;
 uint8_t green;
 uint8_t blue;
};

struct bitmap {
 struct RGBPixel *data;
 size_t width;
 size_t height;
 size_t bytesPerPixel;
 size_t bytewidth;
 /* etc. */
};

I suppose the simplest way would be this:

struct RGBPixel {
 uint8_t red;
 uint8_t green;
 uint8_t blue;
 bool transparent;
};

But that seems a bit wasteful (you might as well add a full alpha channel). The only other possibility I can think of is to reserve one of the colors as being transparent, but then you lose the ability to display that color. Is there a standard way to do this?

How do common formats (GIF, 8-bit PNG, etc.) represent this?


Solution

  • There are 16M colors, designating one of them as transparent will not be a big hardship. Unless your image is 16 megapixels, you can be sure it doesn't even use all 16M colors anyway, just pick one that isn't used and make it the transparency color. If you do have a huge image that uses them all, select the one that is least used and change it to an adjacent color, making it unused.

    As you indicated, trying to store a single bit per pixel with the pixel RGB data isn't efficient. You should probably either store all the RGB pixels in one pointer and then a bitmap of the same H and V dimensions in another pointer, or you can do chroma keying. You could store the data with R,G,B and transparency bitmap separately as mentioned above but that's generally very inefficient when it comes to drawing it.