通过浏览按钮显示图像 [英] Display Image From browse button

查看:118
本文介绍了通过浏览按钮显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,我正在使用Visual Studio 2012的MFC 如何通过浏览按钮在图片控件中显示图像? 在单击浏览按钮时,我将路径设置为类似

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框架带有CImage类,该类允许您加载图像(支持PNG,JPEG,BMP,GIF和其他格式).为了在优化校准中显示目标图像,您需要使用CStatic::SetBitmap()方法. CImage类实现了Detach()方法,该方法使您可以直接访问HBITMAP对象.这是一个示例:

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:

m_PictureCtrl是在对话框窗口头文件中定义的,如下所示:

The m_PictureCtrl is defined in your dialog window header file like this:

CStatic m_PictureCtrl;

使用标准的 MFC数据交换机制将其映射到IDC_PIC_STATIC控件ID.

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);
}

这篇关于通过浏览按钮显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆