我试图按照本文中的指示将像素数组转换为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