除了已经给出的好的答案之外,这里有一个如何获得简单数组结构的示例。(您可以使用例如Goz 的代码进行迭代。)
GetDIBits 参考@MSDN
您必须选择DIB_RGB_COLORS
作为标志uUsage
并设置BITMAPINFO
结构及其包含的BITMAPINFOHEADER
结构。当您将biClrUsed
和biClrImportant
设置为零时,“没有”颜色表,因此您可以读取从位图的像素GetDIBits
作为 RGB 值序列。使用32
as bit count ( biBitCount
) 根据 MSDN 设置数据结构:
位图最多有 2^32 种颜色。如果是的biCompression
成员,则BITMAPINFOHEADER
是BI_RGB
的bmiColors
成员。位图数组中的每一个分别代表一个像素的蓝色、绿色和红色的相对强度。不使用每个中的高字节。BITMAPINFO
NULL
DWORD
DWORD
由于 MSLONG
的长度正好为 32 位(大小为 a DWORD
),因此您不必注意填充(如备注部分所述)。
代码:
HDC hdcSource = NULL; // the source device context
HBITMAP hSource = NULL; // the bitmap selected into the device context
BITMAPINFO MyBMInfo = {0};
MyBMInfo.bmiHeader.biSize = sizeof(MyBMInfo.bmiHeader);
// Get the BITMAPINFO structure from the bitmap
if(0 == GetDIBits(hdcSource, hSource, 0, 0, NULL, &MyBMInfo, DIB_RGB_COLORS))
{
// error handling
}
// create the pixel buffer
BYTE* lpPixels = new BYTE[MyBMInfo.bmiHeader.biSizeImage];
// We'll change the received BITMAPINFOHEADER to request the data in a
// 32 bit RGB format (and not upside-down) so that we can iterate over
// the pixels easily.
// requesting a 32 bit image means that no stride/padding will be necessary,
// although it always contains an (possibly unused) alpha channel
MyBMInfo.bmiHeader.biBitCount = 32;
MyBMInfo.bmiHeader.biCompression = BI_RGB; // no compression -> easier to use
// correct the bottom-up ordering of lines (abs is in cstdblib and stdlib.h)
MyBMInfo.bmiHeader.biHeight = abs(MyBMInfo.bmiHeader.biHeight);
// Call GetDIBits a second time, this time to (format and) store the actual
// bitmap data (the "pixels") in the buffer lpPixels
if(0 == GetDIBits(hdcSource, hSource, 0, MyBMInfo.bmiHeader.biHeight,
lpPixels, &MyBMInfo, DIB_RGB_COLORS))
{
// error handling
}
// clean up: deselect bitmap from device context, close handles, delete buffer