请问有人做过MFC吗?有个问题
我想在一个dialog上显示一张JPG图片,怎么弄
通过OLE实现,具体代码给你参考一下
CFileDialog fd(TRUE);
fd.m_ofn.lpstrFilter="jpg文件.bmp文件\0*.jpg;*.bmp\0\0";
if ( fd.DoModal() != IDOK )
{
return;
}
CString m_Path="";
m_Path=fd.GetPathName();
IStream *pStm;
CFileStatus fstatus;
CFile file;
LONG cb;
HGLOBAL hGlobal;
if (file.Open(m_Path,CFile::modeRead) &&
file.GetStatus(m_Path,fstatus) && ((cb = fstatus.m_size) != -1))
{
hGlobal = GlobalAlloc(GMEM_MOVEABLE, cb);
LPVOID pvData = NULL;
if (hGlobal != NULL)
{
if ((pvData = GlobalLock(hGlobal)) != NULL)
{
file.ReadHuge(pvData, cb);
GlobalUnlock(hGlobal);
CreateStreamOnHGlobal(hGlobal, TRUE, &pStm);
}
}
}
CDC * pDC=GetDC();
IPicture *pPic;
if(SUCCEEDED(OleLoadPicture(pStm,fstatus.m_size,TRUE,IID_IPicture,(LPVOID*)&pPic)))
{
OLE_XSIZE_HIMETRIC hmWidth;
OLE_YSIZE_HIMETRIC hmHeight;
pPic->get_Width(&hmWidth);
pPic->get_Height(&hmHeight);
double fX,fY;
fX = (double)pDC->GetDeviceCaps(HORZRES)*(double)hmWidth/((double)pDC->GetDeviceCaps(HORZSIZE)*100.0);
fY = (double)pDC->GetDeviceCaps(VERTRES)*(double)hmHeight/((double)pDC->GetDeviceCaps(VERTSIZE)*100.0);
CString str;
str.Format("%f,%f",(double)fX,(double)fY);
// MessageBox(str);
/* if(FAILED(pPic->Render(*pDC,0,0,(DWORD)fX,(DWORD)fY,0,hmHeight,hmWidth,-hmHeight,NULL)))
{ AfxMessageBox("渲染图像失败!"); }*/
if(FAILED(pPic->Render(*pDC,0,0,(DWORD)fX,(DWORD)fY,0,hmHeight,hmWidth,-hmHeight,NULL)))
{ AfxMessageBox("渲染图像失败!"); }
pPic->Release();
}
else
{AfxMessageBox("从流中装载图像失败!");
}
ReleaseDC(pDC);
GlobalFree(hGlobal);
这里还有另外一种方法,就是将JPG转换成HBITMAP句丙后操纵
HBITMAP JpgToBmp(LPCTSTR szFile, HBITMAP hRet)
{
LPPICTURE gpPicture;
HANDLE hFile = ::CreateFile(szFile, GENERIC_READ,0,NULL,
OPEN_EXISTING, 0,NULL);
if(INVALID_HANDLE_VALUE == hFile)
return false;
DWORD dwFileSize = ::GetFileSize(hFile,NULL);
ASSERT(-1!=dwFileSize);
LPVOID pvData = NULL;
HGLOBAL hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, dwFileSize);
ASSERT(NULL!=hGlobal);
pvData = ::GlobalLock(hGlobal);
ASSERT(NULL!=pvData);
DWORD dwBytesRead = 0;
BOOL bRead = ::ReadFile(hFile,pvData,dwFileSize,&dwBytesRead,NULL);
ASSERT(FALSE!= bRead);
::GlobalUnlock(hGlobal);
::CloseHandle(hFile);
LPSTREAM pstm = NULL;
HRESULT hr = ::CreateStreamOnHGlobal(hGlobal,TRUE,&pstm);
ASSERT(SUCCEEDED(hr)&&pstm);
hr=::OleLoadPicture(pstm,dwFileSize,FALSE,IID_IPicture,
(LPVOID*)&gpPicture);
ASSERT(SUCCEEDED(hr)&&gpPicture);
pstm->Release();
OLE_HANDLE picHandle;
gpPicture->get_Handle(&picHandle);
HDC hdc = ::CreateCompatibleDC(NULL);
ASSERT(hdc);
::SelectObject(hdc,(HGDIOBJ)picHandle);
hRet = (HBITMAP)::GetCurrentObject(hdc,OBJ_BITMAP);
DeleteDC(hdc);
return hRet;
}
用法
HBITMAP hbitmap;
hbitmap = JpgToBmp("你的jpg文件路径",hbitmap);
返回一个HBITMAP句柄