Abstract
CreateGrayscaleIcon
is a Win32 function that creates a grayscale icon starting from a given icon.
The resulting icon will have the same size of the original one. This function is written using only Win32 APIs
to make possible to be used either in MFC and pure Win32 applications.
Function description
Just add in your project a function like the following:
HICON CreateGrayscaleIcon(HICON hIcon)
{
HICON hGrayIcon = NULL;
HDC hMainDC = NULL, hMemDC1 = NULL, hMemDC2 = NULL;
BITMAP bmp;
HBITMAP hOldBmp1 = NULL, hOldBmp2 = NULL;
ICONINFO csII, csGrayII;
BOOL bRetValue = FALSE;
bRetValue = ::GetIconInfo(hIcon, &csII);
if (bRetValue == FALSE) return NULL;
hMainDC = ::GetDC(NULL);
hMemDC1 = ::CreateCompatibleDC(hMainDC);
hMemDC2 = ::CreateCompatibleDC(hMainDC);
if (hMainDC == NULL || hMemDC1 == NULL || hMemDC2 == NULL) return NULL;
if (::GetObject(csII.hbmColor, sizeof(BITMAP), &bmp))
{
DWORD dwWidth = csII.xHotspot*2;
DWORD dwHeight = csII.yHotspot*2;
csGrayII.hbmColor = ::CreateBitmap(dwWidth, dwHeight, bmp.bmPlanes,
bmp.bmBitsPixel, NULL);
if (csGrayII.hbmColor)
{
hOldBmp1 = (HBITMAP)::SelectObject(hMemDC1, csII.hbmColor);
hOldBmp2 = (HBITMAP)::SelectObject(hMemDC2, csGrayII.hbmColor);
DWORD dwLoopY = 0, dwLoopX = 0;
COLORREF crPixel = 0;
BYTE byNewPixel = 0;
for (dwLoopY = 0; dwLoopY < dwHeight; dwLoopY++)
{
for (dwLoopX = 0; dwLoopX < dwWidth; dwLoopX++)
{
crPixel = ::GetPixel(hMemDC1, dwLoopX, dwLoopY);
byNewPixel = (BYTE)((GetRValue(crPixel) * 0.299) +
(GetGValue(crPixel) * 0.587) +
(GetBValue(crPixel) * 0.114));
if (crPixel) ::SetPixel(hMemDC2, dwLoopX, dwLoopY,
RGB(byNewPixel, byNewPixel,
byNewPixel));
}
}
::SelectObject(hMemDC1, hOldBmp1);
::SelectObject(hMemDC2, hOldBmp2);
csGrayII.hbmMask = csII.hbmMask;
csGrayII.fIcon = TRUE;
hGrayIcon = ::CreateIconIndirect(&csGrayII);
}
::DeleteObject(csGrayII.hbmColor);
}
::DeleteObject(csII.hbmColor);
::DeleteObject(csII.hbmMask);
::DeleteDC(hMemDC1);
::DeleteDC(hMemDC2);
::ReleaseDC(NULL, hMainDC);
return hGrayIcon;
}
History
- 03/May/2002
Removed dependancy from m_hWnd
Removed 1 BitBlt operation
- 16/April/2002
First release
Disclaimer
THE SOFTWARE AND THE ACCOMPANYING FILES ARE DISTRIBUTED "AS IS" AND WITHOUT ANY WARRANTIES WHETHER EXPRESSED OR IMPLIED.
NO RESPONSIBILITIES FOR POSSIBLE DAMAGES OR EVEN FUNCTIONALITY CAN BE TAKEN.
THE USER MUST ASSUME THE ENTIRE RISK OF USING THIS SOFTWARE.
Terms of use
THIS SOFTWARE IS FREE FOR PERSONAL USE OR FREEWARE APPLICATIONS.