4,448
社区成员
发帖
与我相关
我的任务
分享
bool CxImage::GrayScale()
{
if (!pDib) return false;
if (head.biBitCount<=8){
RGBQUAD* ppal=GetPalette();
int gray;
//converts the colors to gray, use the blue channel only
for(DWORD i=0;i<head.biClrUsed;i++){
gray=(int)RGB2GRAY(ppal[i].rgbRed,ppal[i].rgbGreen,ppal[i].rgbBlue);
ppal[i].rgbBlue = (BYTE)gray;
}
// preserve transparency
if (info.nBkgndIndex >= 0) info.nBkgndIndex = ppal[info.nBkgndIndex].rgbBlue;
//create a "real" 8 bit gray scale image
if (head.biBitCount==8){
BYTE *img=info.pImage;
for(DWORD i=0;i<head.biSizeImage;i++) img[i]=ppal[img[i]].rgbBlue;
SetGrayPalette();
}
//transform to 8 bit gray scale
if (head.biBitCount==4 || head.biBitCount==1){
CxImage ima;
ima.CopyInfo(*this);
if (!ima.Create(head.biWidth,head.biHeight,8,info.dwType)) return false;
ima.SetGrayPalette();
#if CXIMAGE_SUPPORT_SELECTION
ima.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
ima.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
for (long y=0;y<head.biHeight;y++){
BYTE *iDst = ima.GetBits(y);
BYTE *iSrc = GetBits(y);
for (long x=0;x<head.biWidth; x++){
//iDst[x]=ppal[BlindGetPixelIndex(x,y)].rgbBlue;
if (head.biBitCount==4){
BYTE pos = (BYTE)(4*(1-x%2));
iDst[x]= ppal[(BYTE)((iSrc[x >> 1]&((BYTE)0x0F<<pos)) >> pos)].rgbBlue;
} else {
BYTE pos = (BYTE)(7-x%8);
iDst[x]= ppal[(BYTE)((iSrc[x >> 3]&((BYTE)0x01<<pos)) >> pos)].rgbBlue;
}
}
}
Transfer(ima);
}
} else { //from RGB to 8 bit gray scale
BYTE *iSrc=info.pImage;
CxImage ima;
ima.CopyInfo(*this);
if (!ima.Create(head.biWidth,head.biHeight,8,info.dwType)) return false;
ima.SetGrayPalette();
#if CXIMAGE_SUPPORT_SELECTION
ima.SelectionCopy(*this);
#endif //CXIMAGE_SUPPORT_SELECTION
#if CXIMAGE_SUPPORT_ALPHA
ima.AlphaCopy(*this);
#endif //CXIMAGE_SUPPORT_ALPHA
BYTE *img=ima.GetBits();
long l8=ima.GetEffWidth();
long l=head.biWidth * 3;
for(long y=0; y < head.biHeight; y++) {
for(long x=0,x8=0; x < l; x+=3,x8++) {
img[x8+y*l8]=(BYTE)RGB2GRAY(*(iSrc+x+2),*(iSrc+x+1),*(iSrc+x+0));
}
iSrc+=info.dwEffWidth;
}
Transfer(ima);
}
return true;
}