有时灰度图像比颜色图像更具有表达效果,
下面的函数DrawGrayScale() 实现了灰度图像的绘制,它仅能处理256色。
如果显示卡支持256色调色板,函数将从DIB的颜色信息中创建灰度调色板,在绘制图像到设备环境前,实现该调色板。
灰度颜色与红、绿和蓝颜色相等同,如果显示卡支持256色以上,它将不支持调色板,调色板操作也不会正常工作,
这样,就得改变DIB中的颜色表,在显示位图之前,改变所有的颜色项。
- // DrawGrayScale - Draws a bitmap in gray scale
- // pDC - Pointer to target device context
- // hDIB - Handle of device-independent bitmap
- //
- void DrawGrayScale( CDC *pDC, HANDLE hDIB )
- {
- CPalette pal;
- CPalette *pOldPalette;
- BITMAPINFO &bmInfo = *(LPBITMAPINFO)hDIB ;
-
- int nColors = bmInfo.bmiHeader.biClrUsed ? bmInfo.bmiHeader.biClrUsed :
- 1 << bmInfo.bmiHeader.biBitCount; // Create the palette if needed if( pDC-GetDeviceCaps(RASTERCAPS) & RC_PALETTE && nColors <= 256 ) { // The device supports a palette and bitmap has color table // Allocate memory for a palette UINT nSize="sizeof(LOGPALETTE)" + (sizeof(PALETTEENTRY) * nColors); LOGPALETTE *pLP="(LOGPALETTE" *) new BYTE[nSize]; pLP-palVersion = 0x300;
- pLP->palNumEntries = nColors;
-
- for( int i=0; i <ncolors; i++) { long lSquareSum="bmInfo.bmiColors[i].rgbRed" * bmInfo.bmiColors[i].rgbRed + bmInfo.bmiColors[i].rgbGreen * bmInfo.bmiColors[i].rgbGreen + bmInfo.bmiColors[i].rgbBlue * bmInfo.bmiColors[i].rgbBlue; int nGray="(int)sqrt(((double)lSquareSum)/3);" pLP-palPalEntry[i].peRed = nGray;
- pLP->palPalEntry[i].peGreen = nGray;
- pLP->palPalEntry[i].peBlue = nGray;
- pLP->palPalEntry[i].peFlags = 0;
- }
-
- pal.CreatePalette( pLP );
-
- delete[] pLP;
- // Select the palette
- pOldPalette = pDC->SelectPalette(&pal, FALSE);
- pDC->RealizePalette();
- }
- else if((pDC->GetDeviceCaps(RASTERCAPS) & RC_PALETTE) == 0 && nColors <= 256 ) { // Device does not supports palettes but bitmap has a color table // Modify the bitmaps color table directly // Note : This ends up changing the DIB. If that is not acceptable then // copy the DIB and then change the copy rather than the original for( int i="0;" i < nColors; i++) { long lSquareSum="bmInfo.bmiColors[i].rgbRed" * bmInfo.bmiColors[i].rgbRed + bmInfo.bmiColors[i].rgbGreen * bmInfo.bmiColors[i].rgbGreen + bmInfo.bmiColors[i].rgbBlue * bmInfo.bmiColors[i].rgbBlue; int nGray="(int)sqrt(((double)lSquareSum)/3);" bmInfo.bmiColors[i].rgbRed="nGray;" bmInfo.bmiColors[i].rgbGreen="nGray;" bmInfo.bmiColors[i].rgbBlue="nGray;" } } int nWidth="bmInfo.bmiHeader.biWidth;" int nHeight="bmInfo.bmiHeader.biHeight;" // Draw the image LPVOID lpDIBBits="(LPVOID)(bmInfo.bmiColors" + nColors); ::SetDIBitsToDevice(pDC-m_hDC, // hDC
- 0, // XDest
- 0, // YDest
- nWidth, // nDestWidth
- nHeight, // nDestHeight
- 0, // XSrc
- 0, // YSrc
- 0, // nStartScan
- nHeight, // nNumScans
- lpDIBBits, // lpBits
- (LPBITMAPINFO)hDIB, // lpBitsInfo
- DIB_RGB_COLORS); // wUsage
-
-
- pDC->SelectPalette(pOldPalette, FALSE);
- }
复制代码
|