我試圖按照本文中的指示將像素數組轉換爲HBITMAP
:How to convert an Array of pixels to HBITMAP。將位數組轉換爲HBITMAP後的空指針
基本上,數組轉換爲HBITMAP
,然後通過複製到剪貼板進行驗證。但是,如果從其成員訪問BITMAP
構造的位值,則返回NULL
。
我可能在這裏缺少一些東西。如果成功創建了HBITMAP
,爲什麼我們仍然會得到指向其位值的NULL
?
uint8 width = 160;
uint8 height = 120;
uint8* pixels = new uint8[160 * 120 * 4];
for (int i = 0; i < 160 * 120 * 4; i++){
pixels[i] = (i % 4 == 1) * 255; // testing pixels
}
BITMAPINFOHEADER bmih;
bmih.biSize = sizeof(BITMAPINFOHEADER);
bmih.biWidth = width;
bmih.biHeight = -1 * height;
bmih.biPlanes = 1;
bmih.biBitCount = 32;
bmih.biCompression = BI_RGB;
bmih.biSizeImage = 0;
bmih.biXPelsPerMeter = 10;
bmih.biYPelsPerMeter = 10;
bmih.biClrUsed = 0;
bmih.biClrImportant = 0;
BITMAPINFO dbmi;
ZeroMemory(&dbmi, sizeof(dbmi));
dbmi.bmiHeader = bmih;
dbmi.bmiColors->rgbBlue = 0;
dbmi.bmiColors->rgbGreen = 0;
dbmi.bmiColors->rgbRed = 0;
dbmi.bmiColors->rgbReserved = 0;
HDC hdc = ::GetDC(NULL);
HBITMAP hbmp = CreateDIBitmap(hdc, &bmih, CBM_INIT, pixels, &dbmi, DIB_RGB_COLORS);
if (hbmp == NULL) {
::MessageBox(NULL, L"Could not load the desired image", L"Error", MB_OK);
return NULL;
}
::ReleaseDC(NULL, hdc);
// a little test if everything is OK
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hbmp); // I can verify the image by pasting
CloseClipboard();
// verify the bitmap
BITMAP bitmap;
::GetObject(hbmp, sizeof(BITMAP), &bitmap);
uint8* lpbits = (uint8*)bitmap.bmBits;
assert(lpbits != NULL); // Why this assertion failed??
// cleanup
// DeleteObject(hbmp);
調用GetLastError來查看調用失敗的原因 - 至少你會得到一個線索 – pm100
@ pm100:大多數GDI函數不會使用GetLastError()來進行錯誤報告,對於使用的GDI函數在這個例子中(只有剪貼板功能)。 –
@RemyLebeau不夠公平。所以沒辦法獲得除了'沒有工作'以外的任何東西。但是,如果某些基礎事件失敗(文件錯誤),那麼GetLastError將返回一些內容(雖然它可能是一條紅色鯡魚)。 – pm100