C/C++:如何在程式中載入JPG圖片?

來源:互聯網
上載者:User
 

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();
來釋放對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.