Display Image From browse button(从浏览按钮显示图像)
问题描述
I am new to C++ and I'm using MFC by Visual Studio 2012 How can I display an Image in a picture control from browse button? On browse button click, I set the path to an edit control like that
void CSimilarityOfImagesDlg::OnBnClickedButton1()
{
CFileDialog dlg(TRUE);
int iRet = dlg.DoModal();
CString path = dlg.GetPathName();
SetWindowText (path);
CEdit* cedit;
cedit = reinterpret_cast<CEdit *>(GetDlgItem(IDC_EDIT1));
cedit->SetWindowTextW(path);
cedit->GetWindowTextW(path);
}
MFC/ATL framework comes with CImage class that allows you to load images (PNG, JPEG, BMP, GIF and other formats are supported). In order to display the target image in your picture control you need to use the CStatic::SetBitmap() method. The CImage class implements Detach() method that allows you to get direct access to HBITMAP object. Here is an example:
The m_PictureCtrl is defined in your dialog window header file like this:
CStatic m_PictureCtrl;
It is mapped to IDC_PIC_STATIC control ID using standard MFC Data Exchange mechanism.
void CTestPicDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_PIC_STATIC, m_PictureCtrl);
}
The Browse Button handler looks like this:
CFileDialog dlg(TRUE);
if (dlg.DoModal() == IDOK)
{
CString sPath = dlg.GetPathName();
CImage img;
HRESULT hr = img.Load(sPath);
if (FAILED(hr))
{
CString sErrorMsg;
sErrorMsg.Format(_T("Failed to load %s"), sPath );
AfxMessageBox(sErrorMsg);
return;
}
CRect rect;
m_PictureCtrl.GetClientRect(rect);
int nWidth = rect.Width();
int nHeight = rect.Height();
CDC* pScreenDC = GetDC();
CDC MemDC;
MemDC.CreateCompatibleDC(pScreenDC);
CBitmap bmp;
bmp.CreateCompatibleBitmap(pScreenDC, nWidth, nHeight);
CBitmap *pOldObj = MemDC.SelectObject(&bmp);
img.StretchBlt(MemDC.m_hDC, 0, 0, nWidth, nHeight, 0, 0, img.GetWidth(), img.GetHeight(), SRCCOPY);
MemDC.SelectObject(pOldObj);
m_PictureCtrl.SetBitmap((HBITMAP)bmp.Detach());
ReleaseDC(pScreenDC);
}
这篇关于从浏览按钮显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从浏览按钮显示图像
基础教程推荐
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
