一. CFileDialog 选择图片文件 CFileDialog m_UpLoadPicDlg(TRUE,NULL,NULL,OFN_FILEMUSTEXIST,_T("图片格式(*.jpg;*.jpeg;*.bmp)|*.jpg;*.jpeg;*.bmp||")); if(m_UpLoadPicDlg.DoModal()!=IDOK) { SetDlgItemText(IDC_EDIT_PIC,_T("")); return; } CString FileName = m_UpLoadPicDlg.GetFileName(); SetDlgItemText(IDC_EDIT_PIC,FileName); CString PathName = m_UpLoadPicDlg.GetPathName(); CString Ext = m_UpLoadPicDlg.GetFileExt(); HWND m_hWnd; GetDlgItem(IDC_STATIC_PIC,&m_hWnd); CWnd *pWnd = GetDlgItem(IDC_STATIC_PIC); CDC *pDC = pWnd->GetDC(); CRect rect; pWnd->GetWindowRect(rect); DisplayPic(PathName,m_hWnd,rect.Width(), rect.Height()); 二. 在Picture控件上画图 HRESULT CPersonManager::DisplayPic(CString lpImageFile, HWND hWnd, int nScrWidth, int nScrHeight) { HDC hDC_Temp=::GetDC(hWnd); IPicture *pPic; IStream *pStm; BOOL bResult; HANDLE hFile=NULL; DWORD dwFileSize,dwByteRead; //打开硬盘中的图形文件 hFile=CreateFile(lpImageFile,GENERIC_READ, FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if (hFile!=INVALID_HANDLE_VALUE) { dwFileSize=GetFileSize(hFile,NULL);//获取文件字节数 if (dwFileSize==0xFFFFFFFF) return E_FAIL; } else { return E_FAIL; } //分配全局存储空间 HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize); LPVOID pvData = NULL; if (hGlobal == NULL) { AfxMessageBox(_T("图形文件分配出错.")); return E_FAIL; } if ((pvData = GlobalLock(hGlobal)) == NULL)//锁定分配内存块 { AfxMessageBox(_T("内存块锁定出问题")); return E_FAIL; } ReadFile(hFile,pvData,dwFileSize,&dwByteRead,NULL);//把文件读入内存缓冲区 GlobalUnlock(hGlobal); if(CreateStreamOnHGlobal(hGlobal, TRUE, &pStm) != S_OK) { AfxMessageBox(_T("流初始化失败")); return E_FAIL; } //装入图形文件 bResult=OleLoadPicture(pStm,dwFileSize,TRUE,IID_IPicture,(LPVOID*)&pPic); if(FAILED(bResult)) { AfxMessageBox(_T("图形文件装载出错.")); return E_FAIL; } OLE_XSIZE_HIMETRIC hmWidth;//图片的真实宽度 OLE_YSIZE_HIMETRIC hmHeight;//图片的真实高度 pPic->get_Width(&hmWidth); pPic->get_Height(&hmHeight); //将图形输出到屏幕上 bResult=pPic->Render(hDC_Temp,0,0,nScrWidth,nScrHeight, 0,hmHeight,hmWidth,-hmHeight,NULL); CloseHandle(hFile);//关闭打开的文件 pPic->Release(); // Free memory. GlobalFree(hGlobal); if (SUCCEEDED(bResult)) { return S_OK; } else { AfxMessageBox(_T("图形文件装载出错.")); return E_FAIL; } }