方法一:
直接从外部文件加载图片
HBITMAP bitmap;
bitmap=(HBITMAP)::LoadImage(AfxGetInstanceHandle(),strFileName,IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
m_backBitmap.DeleteObject();
if(!m_backBitmap.Attach(bitmap))
{
MessageBox("导入背景图失败!","提示",MB_OK);
return;
}
//说明:此方法总是出现ERROR_NOT_ENOUGH_MEMORY错误,错误代码是8.从官方资料中知道,通过LoadImage函数加载的文件不是保存在程序内存中,而是保存在一个叫desktop heap的地方。desktop heap我想更加每个人的配置和使用有关。网上说将要加载的图片做小一点就可以加载成功。遗憾的是我的加载从来没有成功过。
方法二:
通过IPicture的方法。通过IPicture的方法,可以加载jpg,gif格式的图片。实现如下所示:
IPicture *pPic = NULL;
IStream *pStm = NULL;
CFileStatus fstatus;
CFile file;
LONG cb;
//打开图片
try
{
if( !file.Open( strPicPath ,CFile::modeRead) )
{
file.Close();
return 0;
}
}
catch( CFileException e )
{
file.Close();
return 0;
}
//申请内存
if( file.GetStatus( strPicPath, fstatus) && ((cb = (LONG)fstatus.m_size) != -1 ) )
{
HGLOBAL hGlobal = NULL;
hGlobal = GlobalAlloc( GMEM_MOVEABLE, cb );
if( hGlobal == NULL )
{
AfxMessageBox( _T("图片内存申请失败。") );
}
//显示错误码
int errCode = GetLastError();
if( errCode != 0 )
{
CString strT;
strT.Format( _T("%d-3"), errCode );
AfxMessageBox( strT );
}
LPVOID pvData = NULL;
if( hGlobal != NULL )
{
//读取内存,进行操作
if( (pvData = GlobalLock(hGlobal) ) != NULL )
{
UINT mGetPicLong = file.Read( pvData, cb);
if( mGetPicLong != cb )
{
GlobalUnlock(hGlobal);
GlobalFree( hGlobal );
file.Close();
return 0;
}
GlobalUnlock(hGlobal);
CreateStreamOnHGlobal( hGlobal,TRUE, &pStm);
int errCode = GetLastError();
if( errCode != 0 )
{
CString strT;
strT.Format( _T("%d-1"), errCode );
AfxMessageBox( strT );
}
if( SUCCEEDED( OleLoadPicture( pStm, (LONG)fstatus.m_size, TRUE, IID_IPicture, (LPVOID*)&pPic ) ) )
{
OLE_XSIZE_HIMETRIC hmWidth;
OLE_YSIZE_HIMETRIC hmHeight;
pPic->get_Width(&hmWidth);
pPic->get_Height(&hmHeight);
CSize sz( hmWidth, hmHeight );
pDC->HIMETRICtoDP( &sz );
if( FAILED(pPic->Render(*pDC,0,0,sz.cx,sz.cy,0,hmHeight,hmWidth,-hmHeight,NULL)))
{
AfxMessageBox(_T("渲染背景图出错"));
}
pPic->Release();
pPic = NULL;
}
else
{
AfxMessageBox(_T("从流中加载图片出错"));
}//if( SUCCEEDED( OleLoadPicture( pStm, fstatus.m_size, TRUE, IID_IPicture, (LPVOID*)&pPic ) ) )
errCode = GetLastError();
if( errCode != 0 )
{
CString strT;
strT.Format( _T("%d-2"), errCode );
AfxMessageBox( strT );
}
pStm->Release(); //释放流
pStm = NULL;
}
else
{
}//if( (pvData = GlobalLock(hGlobal) ) != NULL )
GlobalFree( hGlobal );
}//if( hGlobal != NULL )
} //if( file.GetStatus( strPicPath, fstatus) && ((cb = fstatus.m_size) != -1 ) )
if( file != NULL )
{
file.Close();
}
//说明:通过此方法可以成功加载jpg图片,屡试不爽。