不用DIB将位图读入CBitmap

不用DIB将位图读入CBitmap
ReadBmpToMem(CString& strPath)
{
 CFile photoBmp;
 //打开指定文件
 if (photoBmp.Open(strPath, CFile::modeRead))
 {
  LONG fileSize=(LONG)photoBmp.GetLength();
  //分配内存
  char *pDib=new char[fileSize+1];
  //读取内存
  if (photoBmp.Read(pDib,fileSize)==(DWORD)fileSize)
  {
   BITMAPFILEHEADER bmfHeader;
   DWORD bmfHeaderLen=sizeof(bmfHeader);
   //char *strncpy( char *strDest, const char *strSource, size_t count);
   ::strncpy((LPSTR)&bmfHeader,(LPSTR)pDib,bmfHeaderLen);
   if (bmfHeader.bfType==(*(WORD*)"BM"))
   {
    LPSTR lpDIB =pDib+ bmfHeaderLen;
    BITMAPINFOHEADER &bmiHeader = *(LPBITMAPINFOHEADER)lpDIB;
    BITMAPINFO &bmInfo = *(LPBITMAPINFO)lpDIB;    
    LPVOID lpDIBBits =pDib+((BITMAPFILEHEADER*)pDib)->bfOffBits;
    //创建设备上下文
    CWindowDC dc(this);
    HBITMAP hBmp = CreateDIBitmap(dc.m_hDC, &bmiHeader,
     CBM_INIT,lpDIBBits, &bmInfo, DIB_RGB_COLORS);
    if (m_Bitmap.GetSafeHandle()!=NULL)
    {
     m_Bitmap.DeleteObject();
    }
    //将位图绑定到指定对象
    m_Bitmap.Attach(hBmp);
   }
  }
  delete[] pDib;
  pDib = NULL; 
     InvalidateRect(&m_recOffset,TRUE);
 }
}

你可能感兴趣的:(不用DIB将位图读入CBitmap)