Icon 转 Bitmap
阅读原文时间:2023年07月15日阅读:1

HBITMAP IconToBitmap(HICON hIcon, SIZE* pTargetSize = NULL)
{
ICONINFO info = {};
if(hIcon == NULL
|| !GetIconInfo(hIcon, &info)
|| !info.fIcon)
{
return NULL;
}

INT nWidth = ;  
INT nHeight = ;  
if(pTargetSize != NULL)  
{  
    nWidth = pTargetSize->cx;  
    nHeight = pTargetSize->cy;  
}  
else  
{  
    if(info.hbmColor != NULL)  
    {  
        BITMAP bmp = {};  
        GetObject(info.hbmColor, sizeof(bmp), &bmp);

        nWidth = bmp.bmWidth;  
        nHeight = bmp.bmHeight;  
    }  
}

if(info.hbmColor != NULL)  
{  
    DeleteObject(info.hbmColor);  
    info.hbmColor = NULL;  
}

if(info.hbmMask != NULL)  
{  
    DeleteObject(info.hbmMask);  
    info.hbmMask = NULL;  
}

if(nWidth <=  
    || nHeight <= )  
{  
    return NULL;  
}

INT nPixelCount = nWidth \* nHeight;

CDC\* pDC = GetDC();  
HDC dc = pDC->GetSafeHdc();  
INT\* pData = NULL;  
HDC dcMem = NULL;  
HBITMAP hBmpOld = NULL;  
bool\* pOpaque = NULL;  
HBITMAP dib = NULL;  
BOOL bSuccess = FALSE;

do  
{  
    BITMAPINFOHEADER bi = {};  
    bi.biSize = sizeof(BITMAPINFOHEADER);  
    bi.biWidth = nWidth;  
    bi.biHeight = -nHeight;  
    bi.biPlanes = ;  
    bi.biBitCount = ;  
    bi.biCompression = BI\_RGB;  
    dib = CreateDIBSection(dc, (BITMAPINFO\*)&bi, DIB\_RGB\_COLORS, (VOID\*\*)&pData, NULL, );  
    if(dib == NULL) break;

    memset(pData, , nPixelCount \* );

    dcMem = CreateCompatibleDC(dc);  
    if(dcMem == NULL) break;

    hBmpOld = (HBITMAP)SelectObject(dcMem, dib);  
    ::DrawIconEx(dcMem, , , hIcon, nWidth, nHeight, , NULL, DI\_MASK);

    //pOpaque = new(std::nothrow) bool\[nPixelCount\];  
    pOpaque = new bool\[nPixelCount\];  
    if(pOpaque == NULL) break;  
    for (INT i = ; i < nPixelCount; ++i)  
    {  
        pOpaque\[i\] = !pData\[i\];  
    }

    memset(pData, , nPixelCount \* );  
    ::DrawIconEx(dcMem, , , hIcon, nWidth, nHeight, , NULL, DI\_NORMAL);

    BOOL bPixelHasAlpha = FALSE;  
    UINT\* pPixel = (UINT\*)pData;  
    for(INT i = ; i<nPixelCount; ++i, ++pPixel)  
    {  
        if((\*pPixel & 0xff000000) != )  
        {  
            bPixelHasAlpha = TRUE;  
            break;  
        }  
    }

    if(!bPixelHasAlpha)  
    {  
        pPixel = (UINT\*)pData;  
        for(INT i=;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(pDC);

if(!bSuccess)  
{  
    if(dib != NULL)  
    {  
        DeleteObject(dib);  
        dib = NULL;  
    }  
}

return dib;  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器