以下是引用片段: 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("http://a_bear.jpg")); m_bHadLoad=LoadMyJpegFile(strPath,&m_lppi); 就可以顯示jpg圖片了,最后要記得在OnDestroy函數中加入: m_lppi->Release(); 來釋放對象。 |
新聞熱點
疑難解答