c++開啟挑選圖片對話方塊

limengshi138392發表於2020-12-05

#c++開啟挑選圖片對話方塊
##選中圖片返回圖片路徑
檔名:selectImage.h

#ifndef FINDCONTOURS_SELECTIMAGE_H
#define FINDCONTOURS_SELECTIMAGE_H

#include <windows.h>
#include <commdlg.h>
#include <iostream>

using namespace std;

string selectImage(){
    string filename;
    OPENFILENAME ofn;			// 公共對話方塊結構
    TCHAR szFile[MAX_PATH];		// 儲存獲取檔名稱的緩衝區
    ZeroMemory(&ofn, sizeof(OPENFILENAME));
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = NULL;
    ofn.lpstrFile = szFile;
    ofn.lpstrFile[0] = '\0';
    ofn.nMaxFile = sizeof(szFile);
    ofn.lpstrFilter = "All\\0*.*\\0Image\\0*.PNG;*.JPG\0\0"; //過濾規則
    ofn.nFilterIndex = 1;
    ofn.lpstrFileTitle = NULL;
    ofn.nMaxFileTitle = 0;
    ofn.lpstrInitialDir = "C:\\Program Files";	//指定預設路徑
    ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

    if (GetOpenFileName(&ofn))
    {
        cout<<"Success open image! "<<endl;
        OutputDebugString(szFile);
        OutputDebugString("\r\n");
        filename = szFile;
        cout<<filename<<endl;
    }
    return filename;
}

#endif //FINDCONTOURS_SELECTIMAGE_H

##使用方法

#include <iostream>
#include <opencv2/opencv.hpp>
#include "selectImage.h" //引用上面的標頭檔案
int main(){
    String imagePath = selectImage();
    Mat imageSource = imread(imagePath, IMREAD_COLOR);
    if (imageSource.empty()) {
        cout<<"iamge can not found!"<<endl;
        return -1;
    }
    imshow("imageSource", imageSource);
 }

相關文章