C/C++:如何在程序中加載JPG圖片?

 

MFC提供的CWnd只有默認加載BMP文件的接口,對JPG等圖像是不支持的,而實際中經常需要用到非BMP的圖片,加載它們需要使用COM技術。首先寫如下函數:

BOOL LoadMyJpegFile(CString fname,LPPICTURE *lppi)
{
 HANDLE hFile=CreateFile(fname,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);

 if(hFile==INVALID_HANDLE_VALUE)
 {
  CString str;
  str.Format(_T("%s無法被打開"),fname);
  MessageBox(str);
  return FALSE;
 }
 //取得文件大小
 DWORD dwFileSize=GetFileSize(hFile,NULL);

 if((DWORD)-1==dwFileSize)
 {
  CloseHandle(hFile);
  MessageBox(_T("圖像文件是空的"));
  return FALSE;
 }
 //讀取圖像文件
 LPVOID pvData;

 //按文件大小分配內存
 HGLOBAL hGlobal=GlobalAlloc(GMEM_MOVEABLE,dwFileSize);

 if(NULL==hGlobal)
 {
  CloseHandle(hFile);
  MessageBox(_T("內存不足,無法分配足夠內存"));
  return FALSE;
 }

 pvData=GlobalLock(hGlobal);
 if(NULL==pvData)
 {
  GlobalUnlock(hGlobal);
  CloseHandle(hFile);
  MessageBox(_T("無法鎖定內存"));
  return FALSE;
 }

 DWORD dwFileRead=0;
 BOOL bRead=ReadFile(hFile,pvData,dwFileSize,&dwFileRead,NULL);
 GlobalUnlock(hGlobal);
 CloseHandle(hFile);
 if(FALSE==bRead)
 {
  MessageBox(_T("讀文件出錯"));
  return FALSE;
 }

 LPSTREAM pstm=NULL;
 //從已分配內存生成IStream流
 HRESULT hr=CreateStreamOnHGlobal(hGlobal,TRUE,&pstm);

 if(!SUCCEEDED(hr))
 {
  MessageBox(_T("生成流操作失敗"));
  if(pstm!=NULL)
   pstm->Release();
  return FALSE;
 }
 else if(pstm==NULL)
 {
  MessageBox(_T("生成流操作失敗"));
  return FALSE;
 }

 if(!*lppi)
  (*lppi)->Release();
 hr=OleLoadPicture(pstm,dwFileSize,FALSE,IID_IPicture,(LPVOID*)&(*lppi));
 pstm->Release();
 if(!SUCCEEDED(hr))
 {
  MessageBox(_T("加載操作失敗"));
  return FALSE;
 }
 else if(*lppi==NULL)
 {
  MessageBox(_T("加載操作失敗"));
  return FALSE;
 }
 return TRUE;
}

然後在頭文件中加入變量聲明和函數聲明:

BOOL LoadMyJpegFile(CString fname,LPPICTURE *lppi);
 LPPICTURE m_lppi;//加載圖像文件的流
 BOOL m_bHadLoad;//已經加載了背景圖像
然後在OnPaint函數中加入:

  if(m_bHadLoad)
  {
   CDC *pDC=GetDC();
   CRect rc;
   long hmWidth=0;
   long hmHeight=0;
   m_lppi->get_Height(&hmHeight);
   m_lppi->get_Width(&hmWidth);
   GetClientRect(&rc);
   int nWidth,nHeight;
   nWidth=rc.Width();
   nHeight=rc.Height();
   HRESULT hr=m_lppi->Render(pDC->m_hDC,nWidth,0,-nWidth,nHeight,

hmWidth,hmHeight,-hmWidth,-hmHeight,&rc);
  }
在OnInitDialog函數中這樣調用上面的加載函數:

 TCHAR strPath[MAX_PATH];
 memset(strPath,0,MAX_PATH);
 GetCurrentDirectory(MAX_PATH,strPath);
 wcscat_s(strPath,MAX_PATH,_T("//a_bear.jpg"));
 m_bHadLoad=LoadMyJpegFile(strPath,&m_lppi);
就可以顯示jpg圖片了,最後要記得在OnDestroy函數中加入:

 m_lppi->Release();
來釋放對象。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章