如何将Icon转成Bitmap
最近工作中有个需求是将Icon转成带Alpha通道的Bitmap, 虽然网上有不少这方面的文章,但很多都是错的, 这里记录下,或许对后来人有用。
BOOL fIcon;
DWORD xHotspot;
DWORD yHotspot;
HBITMAP hbmMask;
HBITMAP hbmColor;
} ICONINFO;
typedef ICONINFO *PICONINFO;
从上面我们可以看到Icon和cursor的结构基本一样,主要都包括一幅mask位图和一幅color位图
HBITMAP IconToBitmap(HICON hIcon, SIZE* pTargetSize = NULL)
{
ICONINFO info = {0};
if(hIcon == NULL
|| !GetIconInfo(hIcon, &info)
|| !info.fIcon)
{
return NULL;
}
INT nWidth = 0;
INT nHeight = 0;
if(pTargetSize != NULL)
{
nWidth = pTargetSize->cx;
nHeight = pTargetSize->cy;
}
else
{
if(info.hbmColor != NULL)
{
BITMAP bmp = {0};
GetObject(info.hbmColor, sizeof(bmp), &bmp);
nWidth = bmp.bmWidth;
nHeight = bmp.bmHeight;
}
}
if(nWidth <= 0
|| nHeight <= 0)
{
return NULL;
}
INT nPixelCount = nWidth * nHeight;
HDC dc = GetDC(NULL);
INT* pData = NULL;
HDC dcMem = NULL;
HBITMAP hBmpOld = NULL;
bool* pOpaque = NULL;
HBITMAP dib = NULL;
BOOL bSuccess = FALSE;
do
{
BITMAPINFOHEADER bi = {0};
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = nWidth;
bi.biHeight = -nHeight;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
dib = CreateDIBSection(dc, (BITMAPINFO*)&bi, DIB_RGB_COLORS, (VOID**)&pData, NULL, 0);
if(dib == NULL) break;
memset(pData, 0, nPixelCount * 4);
dcMem = CreateCompatibleDC(dc);
if(dcMem == NULL) break;
hBmpOld = (HBITMAP)SelectObject(dcMem, dib);
::DrawIconEx(dcMem, 0, 0, hIcon, nWidth, nHeight, 0, NULL, DI_MASK);
pOpaque = new(std::nothrow) bool[nPixelCount];
if(pOpaque == NULL) break;
for (INT i = 0; i < nPixelCount; ++i)
{
pOpaque[i] = !pData[i];
}
memset(pData, 0, nPixelCount * 4);
::DrawIconEx(dcMem, 0, 0, hIcon, nWidth, nHeight, 0, NULL, DI_NORMAL);
BOOL bPixelHasAlpha = FALSE;
UINT* pPixel = (UINT*)pData;
for(INT i = 0; i<nPixelCount; ++i, ++pPixel)
{
if((*pPixel & 0xff000000) != 0)
{
bPixelHasAlpha = TRUE;
break;
}
}
if(!bPixelHasAlpha)
{
pPixel = (UINT*)pData;
for(INT i=0;i <nPixelCount; ++i, ++pPixel)
{
if(pOpaque[i])
{
*pPixel |= 0xFF000000;
}
else
{
*pPixel &= 0x00FFFFFF;
}
}
}
bSuccess = TRUE;
} while(FALSE);
if(pOpaque != NULL)
{
delete []pOpaque;
pOpaque = NULL;
}
if(dcMem != NULL)
{
SelectObject(dcMem, hBmpOld);
DeleteDC(dcMem);
}
ReleaseDC(NULL, dc);
if(!bSuccess)
{
if(dib != NULL)
{
DeleteObject(dib);
dib = NULL;
}
}
return dib;
}
另外感慨Webkit是个宝库, 我们的Icon转Bitmap代码实际上可以参考这里:
http://www.cnblogs.com/weiym/p/3928348.html