为什么我打开的图像比原图失真很多呢?还有就是我的程序运行之后,有的时候图像文件能打开,同时也就运行“AfxMessageBox("The file is opened");”这一句,而有的时候图像文件打不开,而且“AfxMessageBox("The file is opened");”这一句代码也不运行,就是不知道原因,我的图像文件都是标准的BMP图。
我的代码如下:
打开代码:
void CTBinView::OnFileOpen()
{
static char szFilter[] = "BMP Files(*.BMP)|*.BMP||";
CFileDialog FileDlg( TRUE, NULL, NULL,OFN_HIDEREADONLY, szFilter );
if( FileDlg.DoModal() == IDOK && m_Dib.Load( FileDlg.GetPathName() ) )
{
InvalidateRect( NULL, TRUE );
UpdateWindow();
AfxMessageBox("The file is opened");
}
}
其中Load的函数声明如下:
BOOL CDib::Load( const char *pszFilename )
{
CFile cf;
if( !cf.Open( pszFilename, CFile::modeRead ) )
return( FALSE );
DWORD dwDibSize;
dwDibSize =cf.GetLength() - sizeof( BITMAPFILEHEADER );
unsigned char *pDib;
pDib = new unsigned char [dwDibSize];
if( pDib == NULL )
return( FALSE );
BITMAPFILEHEADER BFH;
try{
if( cf.Read( &BFH, sizeof( BITMAPFILEHEADER ) )
!= sizeof( BITMAPFILEHEADER ) ||BFH.bfType != 'MB' ||
cf.Read( pDib, dwDibSize ) != dwDibSize ){
delete [] pDib;
return( FALSE );
}
}
catch( CFileException *e ){
e->Delete();
delete [] pDib;
return( FALSE );
}
if( m_pDib != NULL )
delete m_pDib;
m_pDib = pDib;
m_dwDibSize = dwDibSize;
m_pBIH = (BITMAPINFOHEADER *) m_pDib;
m_pPalette =(RGBQUAD *) &m_pDib[sizeof(BITMAPINFOHEADER)];
m_nPaletteEntries = 1 << m_pBIH->biBitCount;
if( m_pBIH->biBitCount > 8 )
m_nPaletteEntries = 0;
else if( m_pBIH->biClrUsed != 0 )
m_nPaletteEntries = m_pBIH->biClrUsed;
m_pDibBits =&m_pDib[sizeof(BITMAPINFOHEADER)+m_nPaletteEntries*sizeof(RGBQUAD)];
if( m_Palette.GetSafeHandle() != NULL )
m_Palette.DeleteObject();
if( m_nPaletteEntries != 0 ){
LOGPALETTE *pLogPal = (LOGPALETTE *) new char
[sizeof(LOGPALETTE)+
m_nPaletteEntries*sizeof(PALETTEENTRY)];
if( pLogPal != NULL ){
pLogPal->palVersion = 0x300;
pLogPal->palNumEntries = m_nPaletteEntries;
for( int i=0; i<m_nPaletteEntries; i++ ){
pLogPal->palPalEntry[i].peRed =
m_pPalette[i].rgbRed;
pLogPal->palPalEntry[i].peGreen =
m_pPalette[i].rgbGreen;
pLogPal->palPalEntry[i].peBlue =
m_pPalette[i].rgbBlue;
}
m_Palette.CreatePalette( pLogPal );
delete [] pLogPal;
}
}
return( TRUE );
}
显示图像的代码如下:
void CTBinView::OnDraw(CDC* pDC)
{
CTBinDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
RECT Rect;
GetClientRect( &Rect );
m_Dib.SetPalette( pDC );
m_Dib.Draw( pDC, 0, 0,Rect.right, Rect.bottom );
}
其中Draw函数的声明如下:
BOOL CDib::Draw( CDC *pDC, int nX, int nY, int nWidth, int nHeight )
{
if( m_pDib == NULL )
return( FALSE );
if( nWidth == -1 )
nWidth = m_pBIH->biWidth;
if( nHeight == -1 )
nHeight = m_pBIH->biHeight;
StretchDIBits( pDC->m_hDC, nX, nY,
nWidth, nHeight,
0, 0,
m_pBIH->biWidth, m_pBIH->biHeight,
m_pDibBits,
(BITMAPINFO *) m_pBIH,
BI_RGB, SRCCOPY );
return( TRUE );
}