CImage灰度化
BOOL ImageToGray(const CImage& imgSrc, CImage& imgDst) { int maxY = imgSrc.GetHeight(); int maxX = imgSrc.GetWidth(); if (!imgDst.IsNull()) { imgDst.Destroy(); } imgDst.Create(maxX, maxY, 8, 0);//图像大小与imgSrc相同,每个像素占1字节 //为imgDst构造256阶灰度调色表 RGBQUAD ColorTab[256]; for (int i = 0; i < 256; i++) { ColorTab[i].rgbBlue = ColorTab[i].rgbGreen = ColorTab[i].rgbRed = i; } imgDst.SetColorTable(0, 256, ColorTab); //获取指向图像数据的指针 //GetBits 与 GetPitch 关系: //当GetPitch()<0时,GetBits()获得的指针指向最后一行 //当GetPitch()>0时,GetBits()获得的指针指向第一行 byte* pDataDst = NULL; byte* pDataSrc = NULL; if (imgDst.GetPitch() < 0) pDataDst = (BYTE*)imgDst.GetBits() + (imgDst.GetPitch()*(imgDst.GetHeight() - 1)); else pDataDst = (BYTE*)imgDst.GetBits(); if (imgSrc.GetPitch() < 0) pDataSrc = (BYTE*)imgSrc.GetBits() + (imgSrc.GetPitch()*(imgSrc.GetHeight() - 1)); else pDataSrc = (BYTE*)imgSrc.GetBits(); //获取每行图像占用的字节数 int pitchSrc = abs(imgSrc.GetPitch()); int pitchDst = abs(imgDst.GetPitch()); // 获取每个像素占用的字节数 int bitCountSrc = imgSrc.GetBPP() / 8; if (bitCountSrc == 1) { imgDst = imgSrc; return TRUE; } if ((bitCountSrc != 3) && (bitCountSrc != 4)) return FALSE; byte tmpR, tmpG, tmpB; int temGray; for (int i = 0; i < maxY; i++) { for (int j = 0; j < maxX; j++) { byte * ptmpSrc = pDataSrc + pitchSrc*i + j*bitCountSrc; tmpB = *ptmpSrc++; tmpG = *ptmpSrc++; tmpR = *ptmpSrc; temGray = (tmpR * 19595 + tmpG * 38469 + tmpB * 7472) >> 16; *(pDataDst + pitchDst*i + j) = temGray; } } return TRUE; }