Reputation: 4998
I am unable to Create a Monochrome Mask for a 24BPP Colour image with SetBkColor() > BitBlt[SRCCOPY]. The Mask ends up completely Black. The entire thing works only if I use LoadImage() instead to get the HBITMAP.
Bitmap img(L"Ball.bmp");
HBITMAP hBM;
img.GetHBITMAP(Color::White, &hBM);
//hBM = LoadBitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_BALL));
.
.
SelectObject(hDCSrc, hBM);
SetBkColor(RGB(0xFF, 0xFF, oxFF));
BitBlt(hDCMem, 0, 0, img.GetWidth(), img.GetHeight(), hDCSrc, 0, 0, SRCCOPY);
//hDCMem is copletely black; but OK when using LoadImage() instead
Other people with the same problem have suggested using Graphics::GetHDC and doing the required with this DC as a workaround. But why does it not work as it should.
Even this workaround din' work. Please help :(
Upvotes: 0
Views: 1468
Reputation: 2125
Yes, you can construct a monochrome mask out of an 24bpp bitmap with GDI calls only and without scanning the individual pixels, but you have to decide which color in the 24bpp bitmap you want to treat as transparent. See the code below:
HBITMAP Bitmap2Mask(HBITMAP hBm, COLORREF TransparentColor)
{
HBITMAP hBmpMask = 0;
BITMAP bmp;
GetObject(hBm, sizeof(BITMAP), &bmp);
if (bmp.bmBitsPixel == 24) //The question was about 24bpp bitmaps (without an Alpha channel)
{
HDC hDCsrc = CreateCompatibleDC(0);
HBITMAP hBmpOldSrc = (HBITMAP)SelectObject(hDCsrc, hBm);
HDC hDCdest = CreateCompatibleDC(0);
hBmpMask = CreateBitmap(bmp.bmWidth, bmp.bmHeight, 1, 1, NULL);
HBITMAP hBmpOldDest = SelectObject(hDCdest, hBmpMask);
SetBkColor(hDCsrc, TransparentColor);
BitBlt(hDCdest, 0, 0, bmp.bmWidth, bmp.bmHeight, hDCsrc, 0, 0, SRCCOPY); //Everything with the TransparentColor ends up white in the mask (meaning "transparent") while everythig else ends up black (meaning "opaque").
hBmpMask = (HBITMAP)SelectObject(hDCdest, hBmpOldDest); //Push out hBmpMask
SelectObject(hDCsrc, hBmpOldSrc); //Push out the hBm
DeleteDC(hDCdest);
DeleteDC(hDCsrc);
}
return hBmpMask; //return the Monochrome mask
}
You could also accomplish this with the TransparentBlt()
function.
Upvotes: 0