1、通过点击界面浏览按钮选择BMP图像文件。
点击浏览按钮打开文件对话框选择BMP图像文件,得到文件所在的路径目录。关键代码如下:
- void ShowBMPDlg::OnButtonSelectiamge()
- {
- char szFilter[] = "BMP Files (*.bmp)|*.bmp|All Files(*.*)|*.*||";
- CFileDialog dlg( TRUE,"BMP",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,szFilter );
- if(dlg.DoModal() == IDOK)
- {
- strPathName = dlg.GetPathName();
- LoadShowBMPFile(strPathName);
- m_hBitmap = BufferToHBITMAP();
- Invalidate();
- }
- }
2、加载BMP文件到内存
通过得到的BMP图像文件路径目录,加载BMP图像文件到内存中。关键代码如下:
- BOOL ShowBMPDlg::LoadShowBMPFile(const char *pPathname)
- {
- CFile file;
- if( !file.Open( pPathname, CFile::modeRead) )
- return FALSE;
- DWORD m_nFileLen;
- m_nFileLen = file.GetLength();
- m_pBMPBuffer = new char[m_nFileLen + 1];
- if(!m_pBMPBuffer)
- return FALSE;
- if(file.Read(m_pBMPBuffer,m_nFileLen) != m_nFileLen)
- return FALSE;
- return TRUE;
- }
3、将内存中的BMP文件内容转换到HBITMAP
将内存中的BMP文件内容转换成位图句柄。关键代码如下:
- HBITMAP ShowBMPDlg::BufferToHBITMAP()
- {
- HBITMAP hShowBMP;
- LPSTR hDIB,lpBuffer = m_pBMPBuffer;
- LPVOID lpDIBBits;
- BITMAPFILEHEADER bmfHeader;
- DWORD bmfHeaderLen;
- bmfHeaderLen = sizeof(bmfHeader);
- strncpy((LPSTR)&bmfHeader,(LPSTR)lpBuffer,bmfHeaderLen);
- if (bmfHeader.bfType != (*(WORD*)"BM")) return NULL;
- hDIB = lpBuffer + bmfHeaderLen;
- BITMAPINFOHEADER &bmiHeader = *(LPBITMAPINFOHEADER)hDIB ;
- BITMAPINFO &bmInfo = *(LPBITMAPINFO)hDIB ;
- m_bmW = bmiHeader.biWidth;
- m_bmH = bmiHeader.biHeight;
- lpDIBBits=(lpBuffer)+((BITMAPFILEHEADER *)lpBuffer)->bfOffBits;
- CClientDC dc(this);
- hShowBMP = CreateDIBitmap(dc.m_hDC,&bmiHeader,CBM_INIT,lpDIBBits,
- &bmInfo,DIB_RGB_COLORS);
- return hShowBMP;
- }
4、在屏幕上显示BMP图像
双缓冲实现BMP位图显示在屏幕上。关键代码如下:
- void ShowBMPDlg::DrawImage(int x, int y, CDC *pDC)
- {
- HBITMAP OldBitmap;
- CDC MemDC;
- MemDC.CreateCompatibleDC(pDC);
- OldBitmap=(HBITMAP)MemDC.SelectObject(m_hBitmap);
- CBitmap* pBitmap = CBitmap::FromHandle(m_hBitmap);
- if(m_bmW == 0 || m_bmH == 0)
- return ;
- CRect rect;
- GetClientRect(&rect);
- pDC->BitBlt(x,y,rect.Width(),rect.Height(),&MemDC,0,0,SRCCOPY);
- MemDC.SelectObject(OldBitmap);
- }
这个方法是我们经常用的用来在界面上画图的一种方法。
转载于:https://blog.51cto.com/binge518/1150458