问:我想把一幅24位图变为灰度图,为什么这段程序后只有下面三分之一的图像变灰了,其余的都没变void CLineTransView::OnViewToGray() 
{
// 转换为灰度图像
CLineTransDoc* pDoc = GetDocument();

unsigned char* lpSrc;
LPSTR lpDIB; //指向DIB的指针
LPSTR lpDIBBits; //指向DIB像素指针
LONG i,j,x,y; LONG lLineBytes; LONG lBytes;
lpDIB = (LPSTR)::GlobalLock((HGLOBAL)pDoc->GetHDIB()); //找到DIB图像像素起始位置
lpDIBBits = pDoc->GetDibImage()->FindDIBBits(lpDIB);

if(pDoc->GetDibImage()->DIBNumColors(lpDIB) != 256)
{
BeginWaitCursor(); pWidth = pDoc->GetDibImage()->DIBWidth(lpDIB);
pHeight  = pDoc->GetDibImage()->DIBHeight(lpDIB);
lLineBytes = WIDTHBYTES(pWidth*8);
lBytes = WIDTHBYTES(pHeight*8);
for(i=0; i<pHeight; i++)
{
for(j=0; j<pWidth-2; j+=3)
{
DWORD   dGray; 
DWORD   dBlue=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*1+j)); 
DWORD   dGreen=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*1+j+1)); 
DWORD   dRed=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*1+j+2)); 
dGray = (dBlue+dGreen+dRed)/3;
*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*1+j) = dGray;
*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*1+j+1) = dGray;
*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*1+j+2) = dGray;
}
} pDoc->SetModifiedFlag(TRUE);
pDoc->UpdateAllViews(NULL); EndWaitCursor();
}
::GlobalUnlock((HGLOBAL)pDoc->GetHDIB());

}

解决方案 »

  1.   


    怎么能无缘无故乘个1呢?
    应该是:DWORD   dBlue=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j));  
    DWORD   dGreen=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j+1));  
    DWORD   dRed=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j+2));  
    dGray = (dBlue+dGreen+dRed)/3; 
    *((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j) = dGray; 
    *((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j+1) = dGray; 
    *((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j+2) = dGray; 楼主每个循环之间有2/3的重叠。
      

  2.   


    那您的意思是:pWidth是每行像素的个数,不是字节的个数喽?
      

  3.   

    pWidth应该是每行像素的个数,即图象宽
      

  4.   

    DWORD   dBlue=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j*3));  
    DWORD   dGreen=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j*3+1));  
    DWORD   dRed=(DWORD)(*((BYTE*)lpDIBBits+(pHeight-1-i)*pWidth*3+j*3+2));  我把系数改为4,就出错.
    改为3,并在后面的j也乘3,这样就不会只有部分变化了,但是变后的图像放大后可见其极少部分像素并没有真正变灰,这又是为什么呢?
      

  5.   

    这个可能是因为图像的宽度不是4的倍数造成的。
    图像每行的字节数 n = ((pWidth*3)+ 3)/4 *4;
    4字节对齐的;