#define COLORREF2RGB(Color) (Color & 0xff00) | ((Color >> 16) & 0xff) \
| ((Color << 16) &#38; 0xff0000)
HBITMAP ReplaceColor (HBITMAP hBmp,COLORREF cOldColor,COLORREF cNewColor)
{
HBITMAP RetBmp=NULL;
if (hBmp)
{
HDC BufferDC=CreateCompatibleDC(NULL); // 源位图DC
if (BufferDC)
{
SelectObject(BufferDC,hBmp); // 选入DC中
HDC DirectDC=CreateCompatibleDC(NULL); // 目标DC
if (DirectDC)
{
// 获取源位图大小
BITMAP bm;
GetObject(hBmp, sizeof(bm), &#38;bm);
// 初始化BITMAPINFO信息,以便使用CreateDIBSection
BITMAPINFO RGB32BitsBITMAPINFO;
ZeroMemory(&#38;RGB32BitsBITMAPINFO,sizeof(BITMAPINFO));
RGB32BitsBITMAPINFO.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
RGB32BitsBITMAPINFO.bmiHeader.biWidth=bm.bmWidth;
RGB32BitsBITMAPINFO.bmiHeader.biHeight=bm.bmHeight;
RGB32BitsBITMAPINFO.bmiHeader.biPlanes=1;
RGB32BitsBITMAPINFO.bmiHeader.biBitCount=32;
UINT * ptPixels;
HBITMAP DirectBitmap= CreateDIBSection(DirectDC,
(BITMAPINFO *)&#38;RGB32BitsBITMAPINFO,
DIB_RGB_COLORS,(void **)&#38;ptPixels,
NULL, 0);
if (DirectBitmap)
{
HGDIOBJ PreviousObject=SelectObject(DirectDC, DirectBitmap);
BitBlt(DirectDC,0,0,bm.bmWidth,bm.bmHeight,BufferDC,0,0,SRCCOPY);
// 转换 COLORREF 为 RGB
cOldColor=COLORREF2RGB(cOldColor);
cNewColor=COLORREF2RGB(cNewColor);
// 替换颜色
for (int i=((bm.bmWidth*bm.bmHeight)-1);i>=0;i--)
{
if (ptPixels[i]==cOldColor) ptPixels[i]=cNewColor;
}
// 修改位图 DirectBitmap
SelectObject(DirectDC,PreviousObject);
// 完成
RetBmp=DirectBitmap;
}
// 释放DC
DeleteDC(DirectDC);
}
// 释放DC
DeleteDC(BufferDC);
}
}
return RetBmp;
} |