Load and Convert Bitmap Colours

Often one needs to load a bitmap and convert the background colour. 

This routine will convert all instances of one colour in a bitmap (colfrom) to the desired colour (colto).

Useage:

// res     == bitmap resource identifier
// colfrom == the background colour to convert
// colto   == the desired colour.
// to convert to the button colour pass [GetSysColor(COLOR_BTNFACE)] 
HBITMAP LoadConvertBitmapCols(int res, COLORREF colfrom, COLORREF colto)
{

    BITMAP bm;
    // load the bitmap from the resource
    HBITMAP hBitmap = LoadBitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(res));

    if (!hBitmap)
        return NULL;

    // Create memDC and Select the bitmap

     HDC tmp = GetDC(NULL);
    HDC hdcMem = CreateCompatibleDC(tmp);
    HGDIOBJ hOldObject = SelectObject(hdcMem, hBitmap);
    int x, y;

    // Get size
    GetObject(hBitmap, sizeof(bm), &bm);

    // Change the background colour to ColTo
    for (x = 0; x<bm.bmWidth; x++){
        for (y = 0; y<bm.bmHeight; y++){
            if (GetPixel(hdcMem, x, y) == colfrom)
                SetPixel(hdcMem, x, y, colto);
        }
    }

    // Select old object back and delete memDC.
    SelectObject(hdcMem, hOldObject);
    DeleteDC(hdcMem);
     ReleaseDC(NULL, tmp);

    // return the bitmap
    return hBitmap;
}

Back to main page