位图文件显示(VC++)

时间:2022-10-05 11:48:43

 

声明位图信息头:

BITMAPINFOHEADER CTDlg::SetBitMapInfo(UINT w, UINT h)

{

  BITMAPINFOHEADER tBitHeader;

 

  tBitHeader.biSize=sizeof(BITMAPINFOHEADER);

  tBitHeader.biWidth=w;

  tBitHeader.biHeight=h;

  tBitHeader.biPlanes=1;

  tBitHeader.biBitCount=24;

  tBitHeader.biCompression=BI_RGB;

  tBitHeader.biSizeImage=w*h*3;

  tBitHeader.biXPelsPerMeter=0;

  tBitHeader.biYPelsPerMeter=0;

  tBitHeader.biClrUsed=0;

  tBitHeader.biClrImportant=0;

 

  return tBitHeader;

}

//处理button单击事件,添加如下代码:

void CTDlg::OnBUTTONOpenFile() 

{

// TODO: Add your control notification handler code here

   CFileDialog dlg(TRUE,_T("Images"),NULL,OFN_HIDEREADONLY|OFN_FILEMUSTEXIST,_T("BMP图像(*.bmp)|*.bmp|"),this);

   CString FilePath;

   unsigned char*p;UINT w,h;

   if(dlg.DoModal()==IDOK)

   {

     FilePath=dlg.GetPathName();

   }

   p=ReadBuf(FilePath,w,h);

   BITMAPINFOHEADER gBitHeader=SetBitMapInfo(w,h);

   HDC hdc=::GetDC(m_showImage.m_hWnd);

   SetStretchBltMode(hdc,HALFTONE);

   StretchDIBits(hdc,0,0,215,129,0,0,w,h,p,(LPBITMAPINFO)&gBitHeader,DIB_RGB_COLORS,SRCCOPY);

//215 ,129为显示区域大小,可定义为w,h即为文件本事大小

   ::ReleaseDC(m_showImage.m_hWnd,hdc);

   delete p;

}

 

//对上述函数中的ReadBuf(....)进行声明及定义,返回缓存区指针:

unsigned char * CTDlg::ReadBuf(CString FilePath, UINT &w, UINT &h)

{

  CFile file;

  file.Open(FilePath,CFile::modeRead);

  int len=file.GetLength();

  file.Seek(14,CFile::begin);

  len-=14;

  unsigned char *p;

  p=new unsigned char[len];

  file.Read(p,len);

  file.Close();

  BITMAPINFO BitInfo;

  memset(&BitInfo,0,sizeof(BITMAPINFO));

  memcpy(&BitInfo,p,sizeof(BITMAPINFO));

  UINT x=BitInfo.bmiHeader.biWidth;

  UINT y=BitInfo.bmiHeader.biHeight;

  w=x;h=y;

  return p;

}