我正在尝试从兼容的位图(由RGB(0,0,255)
颜色完全填充)到GetDIBits
取一个像素数组,但是它返回了另一种颜色。而且,当我尝试更改数组时,它实际上返回异常。怎么了?
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
HBRUSH hb = CreateSolidBrush(RGB(0, 0, 255));
HDC hdcc = CreateCompatibleDC(hdc);
HBITMAP bm = CreateCompatibleBitmap(hdc, r.right, r.bottom);
SelectObject(hdcc, bm);
SelectObject(hdcc, hb);
Rectangle(hdcc, 0, 0, r.right, r.bottom); //filling by the blue brush
BITMAPINFO bi = { 0 };
bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
int er = GetDIBits(hdcc, bm, 0, 0, NULL, &bi, DIB_RGB_COLORS);
//In GetDIBits, as HDC argument must be compatible, yes?
if (!er)
{
cout << "ERROR HERE:"<< GetLastError()<<"ENDS";
}
COLORREF *buf = new COLORREF(bi.bmiHeader.biSizeImage); //Yet, still, I have not understood, which type array should be - char, BYTE, COLORREF or anything else
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biHeight = abs(bi.bmiHeader.biHeight);
GetDIBits(hdcc, bm, 0, bi.bmiHeader.biHeight, buf, &bi, DIB_RGB_COLORS);
for (int i(0); i < 100; i++)
{
cout << (int)GetRValue(buf[i]) << ",";
cout << (int)GetGValue(buf[i]) << ",";
cout << (int)GetBValue(buf[i]) << ",";
cout << endl;
}
SetDIBits(hdcc, bm, 0, bi.bmiHeader.biHeight, buf, &bi, DIB_RGB_COLORS);
delete []buf;
BitBlt(hdc, 0, 0, r.right, r.bottom, hdcc, 0, 0, SRCCOPY);
DeleteObject(hb);
DeleteDC(hdcc);
DeleteObject(bm);
EndPaint(hwnd, &ps);
}
break;
enter image description here
最佳答案
这条线有几个问题:
COLORREF *buf = new COLORREF(bi.bmiHeader.biSizeImage);
正如@PaulMcKenzie指出的那样,您打算使用方括号而不是括号,以便为数组分配空间。
biSizeImage
以字节为单位,而不是COLORREF
s,因此这会过度分配。biSizeImage
可能为零,在这种情况下,您将不会分配任何东西。当biSizeImage
为零时,这意味着您必须计算所需的实际大小。在程序的这一点上,
biSizeImage
是与设备有关的(“兼容”)位图的大小,它可能与您试图获取的与设备无关的数据所需的大小完全不同。