为什么在VC++中调用.BMP文件出现颜色失真?
似乎只有在桌面设置为真彩色、图片是真彩色的时候才不会有问题。请教大家如何修改我的代码才能使在桌面或者位图不是真彩色的时候也能够正常显示图片?
BOOL CDIB::LoadFromFile(LPCTSTR IpszFileName)
{
CFile file;
BITMAPINFO * pBMI=NULL;
BYTE * pDIBData=NULL;
if(!file.Open(IpszFileName,CFile::modeRead|CFile::typeBinary))
{
AfxMessageBox("Cannot Open File!");
return FALSE;
}
BITMAPFILEHEADER bfh;
if (file.Read(&bfh,sizeof(bfh))!=sizeof(bfh))
{
AfxMessageBox("ERROR when reading the file header!");
return FALSE;
}
if (bfh.bfType!=0x4d42)
{
AfxMessageBox("It is not a .BMP file!");
return FALSE;
}
BITMAPINFOHEADER bih;
if (file.Read(&bih,sizeof(bih))!=sizeof(bih))
{
AfxMessageBox("ERROR when reading the file header!");
return FALSE;
}
/*
if (bih.biBitCount!=24)
{
AfxMessageBox("Not a 24-bit color BMP!");
return FALSE;
}
*/
pBMI=(BITMAPINFO*) new char[sizeof (BITMAPINFO)];
if (!pBMI)
{
AfxMessageBox("ERROR when allocating memory!(pBMI)");
return FALSE;
}
file.Seek(sizeof(bfh),CFile::begin);
if(file.Read(pBMI,sizeof(BITMAPINFO))!=sizeof(*pBMI))
{
AfxMessageBox("Error when reading BitMap Info!");
return FALSE;
}
DWORD dataBytes =bfh.bfSize-bfh.bfOffBits;
pDIBData=(BYTE *)new char[dataBytes];
if(!pDIBData)
{
AfxMessageBox("ERROR when allocating memory!(pDIBData)");
delete pBMI;
return FALSE;
}
DWORD test;
if ((test=file.ReadHuge(pDIBData, dataBytes))!=dataBytes)
{
AfxMessageBox("ERROR when reading file!(ReadHuge)");
delete pBMI;
delete pDIBData;
return FALSE;
}
file.Close();
if (m_pBMI !=NULL)
delete m_pBMI;
m_pBMI=pBMI;
if(m_pDIBData!=NULL)
delete m_pDIBData;
m_pDIBData=pDIBData;
return true;
}
void CDIB::ShowDIB(CDC * pDC,int nLeft,int nTop,int nWidth,int nHeight)
{
pDC->SetStretchBltMode(COLORONCOLOR);
StretchDIBits(pDC->GetSafeHdc(),
nLeft,
nTop,
nWidth,
nHeight,
0,
0,
GetDIBWidth(),
GetDIBHeight(),
m_pDIBData,
m_pBMI,
DIB_RGB_COLORS,
SRCCOPY);
}