MFC显示图片

方法一

1:建立工程之后将面板上的自带按钮删掉,加一个picture控件和button控件。(采用的release  x64)

2:添加include、lib和附加依赖项opencv_core249.lib、opencv_highgui249.lib、opencv_imgproc249.lib(并未测试不加这些会产生什么后果,毕竟新手,一步一步照着来的)

3:xxxxxxDlg.cpp文件中添加#include <iostream>、#include <opencv2/opencv.hpp>、using namespace cv;

4:双击button控件,进入编写代码界面,代码粘贴如下:

void CMFCApplication4Dlg::OnBnClickedButton1()
{
// TODO:  在此添加控件通知处理程序代码
namedWindow("view", WINDOW_AUTOSIZE);
HWND hWnd = (HWND)cvGetWindowHandle("view");
HWND hParent = ::GetParent(hWnd);
::SetParent(hWnd, GetDlgItem(IDC_STATIC)->m_hWnd);
::ShowWindow(hParent, SW_HIDE);


Mat Photo = imread("E:/VS2013/work/1.jpg");


Mat img;
CRect rect;


GetDlgItem(IDC_STATIC)->GetClientRect(&rect);   //获取窗体大小
cv::Rect dst(rect.left, rect.top, rect.right, rect.bottom);
cv::resize(Photo, img, cv::Size(rect.Width(), rect.Height()));
unsigned int m_buffer[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256];
BITMAPINFO* m_bmi = (BITMAPINFO*)m_buffer; BITMAPINFOHEADER* m_bmih = &(m_bmi->bmiHeader);
memset(m_bmih, 0, sizeof(*m_bmih)); m_bmih->biSize = sizeof(BITMAPINFOHEADER);
m_bmih->biWidth = img.cols;
m_bmih->biHeight = -img.rows; // 在自下而上的位图中 高度为负 
m_bmih->biPlanes = 1;
m_bmih->biCompression = BI_RGB;
m_bmih->biBitCount = 8 * img.channels();
CDC *pDC = GetDlgItem(IDC_STATIC)->GetDC();
::StretchDIBits(pDC->GetSafeHdc(), 0, 0, rect.Width(), rect.Height(), 0, 0, rect.Width(), rect.Height(), img.data, (BITMAPINFO*)m_bmi, DIB_RGB_COLORS, SRCCOPY); ReleaseDC(pDC);


imshow("view", img);

}

5:运行代码

MFC显示图片