如何在程序中加载JPG图片?

来源:互联网 发布:cn域名必须备案吗 编辑:程序博客网 时间:2024/04/29 09:22

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();
来释放对象。

原创粉丝点击