vc 加载bmp位图并显示的方法
方法一、显示位图文件
[cpp] view plaincopy- HBITMAP hBitmap=(HBITMAP)LoadImage(NULL,_T(“xxx.bmp”),Image_Bitmap,0,0,Lr_CreateDibSection|Lr_DefaultSize|Lr_LoadFromFile);
- //加载bmp文件 xxx.bmp 就是要加载的图片名字
- CBitmap bitmap; bitmap.Attach(hBitmap); //关联位图对象
- CDC dcimage;dcimage.CreateCompatibleDC(pDC); //内存
- DCBITMAP bmp;bitmap.GetBitmap(&bmp); //获取位图信息
- dcimage.SelectObject(&bitmap); //选取位图对象
- pDC->BitBlt(0,0,bmp.bmWidth,bmp.bmHeight,&dcimage,0,0,SRCCOPY); //显示
方法二、用文件打开对话框选取图片
你建立一个基于对话框的程序,在主对话框上加载一个 PictureBox,然后加载一个Button,添加点击Button事件。
具体代码如下:
CFileDialog dlg(TRUE,"bmp",".bmp",OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,"位图文件(*.BMP)|*.BMP||");
dlg.DoModal();
HBITMAP hBitmap;
HDC hSrcDC;
HDC hDesDC;
CBitmap bmp;
CWnd *hwnd;
RECT rect;
BITMAP bm;
hwnd = GetDlgItem(IDC_STATIC);
hDesDC = hwnd->GetDC()->m_hDC;
hSrcDC = CreateCompatibleDC(hDesDC);
hBitmap=(HBITMAP)LoadImage(AfxGetInstanceHandle(),dlg.GetPathName(),IMAGE_BITMAP,0,0,LR_LOADFROMFILE|LR_CREATEDIBSECTION); GetObject(hBitmap, sizeof BITMAP, &bm);
SelectObject(hSrcDC, hBitmap);
hwnd->GetClientRect(&rect);
::SetStretchBltMode(hDesDC,COLORONCOLOR);
::StretchBlt(hDesDC, rect.left, rect.top, rect.right, rect.bottom, hSrcDC, 0, 0, bm.bmWidth, bm.bmHeight,SRCCOPY);
直接用mfc自带的static 图片控件显示bmp位图资源 方法1:
1) 更改属性Picture Control属性
2) 直接关联上image: 设置Image属性
3) 更改type为Bitmap
方法2:(PictureEx类网上搜)
1)添加控件变量为PictureEx对象
2) 直接m_pic1.LoadBitmap(IDB_BITMAP1);
示例:
1. 关联 Picture Control 对象: m_stPicture
2. 添加2个BMP资源 IDB_BITMAP1, IDB_BITMAP2
3. 定义: HBITMAP m_hBitmap;
4. 一开始显示图片
BOOL CShowBmpDlg::OnInitDialog(){
CDialog::OnInitDialog();
...... //显示图片 m_hBitmap = (HBITMAP)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_BITMAP1), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS);
m_stPicture.ModifyStyle(0xF, SS_BITMAP);
m_stPicture.SetBitmap(m_hBitmap);
return TRUE; // 除非设置了控件的焦点,否则返回 TRUE
}
5. 切换图片
void CShowBmpDlg::OnBnClickedOk(){
static int nId = 0;
nId++;
if (NULL != m_hBitmap)
{
::DeleteObject(m_hBitmap);
m_hBitmap = NULL;
} int nPicId = nId = nId % 2 ? IDB_BITMAP2 : IDB_BITMAP1;
m_hBitmap = (HBITMAP)LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(nPicId), IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS);
m_stPicture.ModifyStyle(0xF, SS_BITMAP);
m_stPicture.SetBitmap(m_hBitmap);
}