变成黑白图片
由于许多图像文件使用颜色表来发挥显示设备的色彩显示能力,因而将一张彩色图片变成黑色图片时需要调用CImage::IsIndexed来判断是否使用颜色表,若是则修改颜色表,否则直接将像素进行颜色设置。例如下面的代码:
| void CEx_ImageView::MakeBlackAndwhite(CImage* image) { if (image->IsNull()) return; if (!image->IsIndexed()) { // 直接修改像素颜色 COLORREF pixel; int maxY = image->GetHeight(), maxX = image->GetWidth(); byte r,g,b,avg; for (int x=0; x<maxX; x++) { for (int y=0; y<maxY; y++) { pixel = image->GetPixel(x,y); r = GetRValue(pixel); g = GetGValue(pixel); b = GetBValue(pixel); avg = (int)((r + g + b)/3); image->SetPixelRGB(x,y,avg,avg,avg); } } } else { // 获取并修改颜色表 int MaxColors = image->GetMaxColorTableEntries(); RGBQUAD* ColorTable; ColorTable = new RGBQUAD[MaxColors]; image->GetColorTable(0,MaxColors,ColorTable); for (int i=0; i<MaxColors; i++) { int avg = (ColorTable[i].rgbBlue + ColorTable[i].rgbGreen + ColorTable[i].rgbRed)/3; ColorTable[i].rgbBlue = avg; ColorTable[i].rgbGreen = avg; ColorTable[i].rgbRed = avg; } image->SetColorTable(0,MaxColors,ColorTable); delete(ColorTable); } } |
至此,我们介绍了GDI+和CImage的一般使用方法和技巧。当然,它们本身还有许多更深入的方法,由于篇幅所限,这里不再一一讨论。

