GetDIBits返回兼容位图的无效颜色数组

问题描述 投票:0回答:1

我试图从兼容的位图(它完全由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

c++ winapi bitmap gdi
1个回答
1
投票

这条线有几个问题:

COLORREF *buf = new COLORREF(bi.bmiHeader.biSizeImage);
  1. 正如@PaulMcKenzie指出的那样,你的意思是使用方括号而不是括号,以便为数组分配空间。
  2. biSizeImage以字节为单位,而不是COLORREFs,因此这会过度分配。
  3. biSizeImage可能为零,在这种情况下你不会分配任何东西。当biSizeImage为零时,表示您必须计算所需的实际大小。
  4. 在程序的这一点上,biSizeImage是设备相关(“兼容”)位图的大小,这可能与您尝试抓取的设备无关数据所需的大小不同。
© www.soinside.com 2019 - 2024. All rights reserved.