VC2010基于对话框使用GDI+显示图像
1.在项目属性中添加GDI+ 静态链接库:
Project->Property->Linker->Input->Additional Dependencies 添加gdiplus.lib 使用。
2. 添加代码
2.1 打开“解决方案资源管理器“,打开“stdafx.h”文件,在其中添加如下代码(添加到本文件的末尾):
#include "gdiplus.h"
using namespace Gdiplus;
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #pragma once #ifndef _SECURE_ATL #define _SECURE_ATL 1 #endif #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers #endif #include "targetver.h" #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit // turns off MFC's hiding of some common and often safely ignored warning messages #define _AFX_ALL_WARNINGS #include <afxwin.h> // MFC core and standard components #include <afxext.h> // MFC extensions #include <afxdisp.h> // MFC Automation classes #ifndef _AFX_NO_OLE_SUPPORT #include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls #endif #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC support for Windows Common Controls #endif // _AFX_NO_AFXCMN_SUPPORT #include <afxcontrolbars.h> // MFC support for ribbons and control bars #ifdef _UNICODE #if defined _M_IX86 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_X64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") #else #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #endif #endif #include "gdiplus.h" using namespace Gdiplus;
2.2 打开“类视图”,选中应用程序类“C×××App”(×××是当前项目的名称),为其添加两个成员变量:
GdiplusStartupInput m_GdiplusStartupInput;
ULONG_PTR m_GdiplusToken;
// Gdipicture.h : main header file for the PROJECT_NAME application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CGdipictureApp: // See Gdipicture.cpp for the implementation of this class // class CGdipictureApp : public CWinApp { public: CGdipictureApp(); // Overrides public: virtual BOOL InitInstance(); virtual BOOL ExitInstance(); GdiplusStartupInput m_GdiplusStartupInput; ULONG_PTR m_GdiplusToken; // Implementation DECLARE_MESSAGE_MAP() }; extern CGdipictureApp theApp;
2.3 在C×××App类的InitInstance函数中添加如下代码:
GdiplusStartup(&m_GdiplusToken,&m_GdiplusStartupInput,NULL);
// Gdipicture.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "Gdipicture.h" #include "GdipictureDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CGdipictureApp BEGIN_MESSAGE_MAP(CGdipictureApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CGdipictureApp construction CGdipictureApp::CGdipictureApp() { // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_RESTART; // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CGdipictureApp object CGdipictureApp theApp; // CGdipictureApp initialization BOOL CGdipictureApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); GdiplusStartup(&m_GdiplusToken,&m_GdiplusStartupInput,NULL); CWinApp::InitInstance(); AfxEnableControlContainer(); // Create the shell manager, in case the dialog contains // any shell tree view or shell list view controls. CShellManager *pShellManager = new CShellManager; // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CGdipictureDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Delete the shell manager created above. if (pShellManager != NULL) { delete pShellManager; } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; } BOOL CGdipictureApp::ExitInstance() { GdiplusShutdown(m_GdiplusToken); return CWinApp::ExitInstance(); }
2.4 重写C×××App类的ExitInstance函数,并添加如下代码:
BOOL CGdipictureApp::ExitInstance()
{
GdiplusShutdown(m_GdiplusToken);
return CWinApp::ExitInstance();
}
3.显示图像的函数
void CGdipictureDlg::DrawImg(CString c_path) { Invalidate();//擦除上一次的图像 UpdateWindow(); int width,height; float rate;//等比例缩小的比例参数 CDC* pDC=GetDC(); Graphics graph(pDC->GetSafeHdc()); //Image* image=Image::FromFile(c_path.AllocSysString());//c_path为图像的路径 Image* image=Image::FromFile(c_path); width=image->GetWidth(); height=image->GetHeight(); CRect rect; GetClientRect(rect); rate=(float)width/(float)height;//宽度和高度的比例 if(height>rect.Height()) { graph.DrawImage(image,0,0,(int)(rate*rect.Height()),rect.Height()); ReleaseDC(pDC); } else { graph.DrawImage(image,0,0); ReleaseDC(pDC); } }
// GdipictureDlg.cpp : implementation file // #include "stdafx.h" #include "Gdipicture.h" #include "GdipictureDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CGdipictureDlg dialog CGdipictureDlg::CGdipictureDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CGdipictureDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CGdipictureDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CGdipictureDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, &CGdipictureDlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON2, &CGdipictureDlg::OnBnClickedButton2) END_MESSAGE_MAP() // CGdipictureDlg message handlers BOOL CGdipictureDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } void CGdipictureDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CGdipictureDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CGdipictureDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CGdipictureDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here DrawImg(_T("E:\\MyCode\\MyOpenCVHelper\\Image\\lena.png")); } void CGdipictureDlg::DrawImg(CString c_path) { Invalidate();//擦除上一次的图像 UpdateWindow(); int width,height; float rate;//等比例缩小的比例参数 CDC* pDC=GetDC(); Graphics graph(pDC->GetSafeHdc()); //Image* image=Image::FromFile(c_path.AllocSysString());//c_path为图像的路径 Image* image=Image::FromFile(c_path); width=image->GetWidth(); height=image->GetHeight(); CRect rect; GetClientRect(rect); rate=(float)width/(float)height;//宽度和高度的比例 if(height>rect.Height()) { graph.DrawImage(image,0,0,(int)(rate*rect.Height()),rect.Height()); ReleaseDC(pDC); } else { graph.DrawImage(image,0,0); ReleaseDC(pDC); } } void CGdipictureDlg::OnBnClickedButton2() { // TODO: Add your control notification handler code here //// Create two images. //Image* image1 = Image::FromFile( _T("E:\\MyCode\\MyOpenCVHelper\\Image\\HappyFish.jpg") ); //Image* image2 = Image::FromFile( _T("E:\\MyCode\\MyOpenCVHelper\\Image\\HappyFish.jpg") ); //// Get a PropertyItem from image1. //PropertyItem* propItem = image1->GetPropertyItem( 20624 ); //// Change the ID of the PropertyItem. //propItem->Id = 20625; //// Set the PropertyItem for image2. //image2->SetPropertyItem( propItem ); //// Draw the image. //e->Graphics->DrawImage( image2, 20.0F, 20.0F ); }
通过上述方法我们可以显示任何一种格式的图像,并且可以等比例调整图像的大小,保证图像不变形。
参考原文:http://blog.csdn.net/tanghuachun/article/details/6603725

浙公网安备 33010602011771号