Why do RGBTRIPLE and RGBQUAD store data in BGR order?
In Windows, the RGBTRIPLE and RGBQUAD structs are defined in reverse order. It is so counterintuitive that I imagine it must have been done deliberately. It doesn't really matter, of course, but this has bugged me enough that I feel it's worth asking. So, why?
The definitions:
typedef struct tagRGBTRIPLE {
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} RGBTRIPLE, *PRGBTRIPLE, NEAR *NPRGBTRIPLE, FAR *LPRGBTRIPLE;
typedef struc开发者_StackOverflow社区t tagRGBQUAD {
BYTE rgbBlue;
BYTE rgbGreen;
BYTE rgbRed;
BYTE rgbReserved;
} RGBQUAD;
On a little endian machine (aka x86 and friends) the structs match the data format of a Bitmap's color data exactly.
The color order storage per-se has absolutely no particular meaning: you could store the components in any order, the important thing is just to agree on which order has been chosen.
Still, the BGR format for these structures matches the components order used for DIBs (at least on little-endian machines - but all the DIB format is designed with LE in mind), so if you have a 24-bit DIB in memory you can read its color data using an RGBTRIPLE
structure and "moving" it using pointer arithmetic; however, the same is not true for 32-bit DIBs and RGBQUAD
(the "reserved" byte should be the first member).
The RGBQUAD
structure is instead used for the palette of DIBs; the padding byte is almost certainly for performance reasons, to allow using directly the palette data read from the file as a lookup table for colors, keeping them on DWORD
boundaries.
So, why was BGR order chosen for DIBs in first place? I suppose that it had some performance advantage at the times DIBs were designed (we're talking about the Presentation Manager of OS/2, ~1988), probably the conversion from DIBs to the in-memory format of most graphic cards was cheaper in this way.
EDIT
Ok, the supposition that the order is a leftover from OS/2 Presentation Manager is confirmed by this 1992 KB article, which specifies explicitly that
Red, green, and blue bytes are in reverse order (red swaps position with blue) from the Windows convention. This is another leftover from Presentation Manager compatibility.
(incidentally, my most-hated leftover from OS/2 PM in DIBs is the reverse order of rows, coming from the default coordinate system used in OS/2 PM)
精彩评论