- BOOL CCdfkDlg::Load(LPCTSTR lpszPathName)
- {
- BOOL bSuccess=FALSE;
- CFile file;
- //打开文件
- if(!file.Open(lpszPathName,CFile::modeRead))
- {
- TRACE(_T("Failed to open file %s,Error %x"),lpszPathName,::GetLastError());
- return FALSE;
- }
- //获取文件大小
- DWORD dwFileSize=file.GetLength();
- //以文件大小为基础分配内存
- LPVOID pvData=NULL;
- HGLOBAL hGlobal=GlobalAlloc(GMEM_MOVEABLE,dwFileSize);
- if(hGlobal==NULL)
- {
- TRACE(_T("Failed to allocate memory for file %s,Error %x"),lpszPathName,::GetLastError());
- return FALSE;
- }
- pvData=GlobalLock(hGlobal);
- if(pvData==NULL)
- {
- TRACE(_T("Failed to lock memory"));
- GlobalFree(hGlobal);
- return FALSE;
- }
- //读取文件,存储到全局内存
- if(file.Read(pvData,dwFileSize)!=dwFileSize)
- {
- TRACE(_T("Failed to read image data from %s,Error:%x"),lpszPathName,::GetLastError());
- GlobalUnlock(hGlobal);
- GlobalFree(hGlobal);
- return FALSE;
- }
- //整理内存,关闭文件句柄
- GlobalUnlock(hGlobal);
- //在全局内存中创建IStream*
- LPSTREAM pStream=NULL;
- if(FAILED(CreateStreamOnHGlobal(hGlobal,TRUE,&pStream)))
- {
- TRACE(_T("Failed to create IStream interface from %s,Error %x"),lpszPathName,::GetLastError());
- GlobalFree(hGlobal);
- return FALSE;
- }
- //从图片文件上创建IPicture
- if (SUCCEEDED(::OleLoadPicture(pStream,dwFileSize,FALSE,IID_IPicture,(LPVOID*)&pPic)))
- {
- short nType=PICTYPE_UNINITIALIZED;
- if(SUCCEEDED(pPic->get_Type(&nType))&&(nType==PICTYPE_BITMAP))
- {
- OLE_HANDLE hBitmap;
- OLE_HANDLE hPalette;
- if(SUCCEEDED(pPic->get_Handle(&hBitmap))&&SUCCEEDED(pPic->get_hPal(&hPalette)))
- {
- m_Bitmap.Attach((HWND)hBitmap);
- m_Palette.Attach((HPALETTE)hPalette);
- bSuccess=TRUE;
- }
- }
- }
- file.Close();
- pStream->Release();
- GlobalFree(hGlobal);
- return bSuccess;
- }
从内存创建cbitmap
最新推荐文章于 2023-05-04 17:37:47 发布