本帖最后由 破帽遮颜 于 2010-6-22 19:08 编辑
BOOL CJPGRES2BMPView::JpgRes2Bmp(UINT ResourceName, LPCSTR ResourceType, HBITMAP *lphBmp)
{
HGLOBAL hGlobal = NULL;
HRSRC hSource = NULL;
LPVOID lpVoid = NULL;
int nSize = 0;
IPicture* p_IPicture = NULL;
OLE_HANDLE hJpegBmp = 0;
// 1. 从资源中读取JPG文件数据
hSource = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(ResourceName), ResourceType);
if(hSource == NULL)
{
return(FALSE);
}
hGlobal = LoadResource(AfxGetResourceHandle(), hSource);
if(hGlobal == NULL)
{
return(FALSE);
}
lpVoid = LockResource(hGlobal);
if(lpVoid == NULL)
{
return(FALSE);
}
nSize = (UINT)SizeofResource(AfxGetResourceHandle(), hSource);
// 2. 分配内存并拷贝数据
HGLOBAL hGlobalMem = GlobalAlloc(GMEM_MOVEABLE, nSize);
if(hGlobalMem == NULL)
{
return(FALSE);
}
void* pData = GlobalLock(hGlobalMem);
memcpy(pData, (BYTE*)hGlobal, nSize);
GlobalUnlock(hGlobalMem);
// 3. 创建Stream
IStream* pStream = NULL;
if(CreateStreamOnHGlobal(hGlobalMem, TRUE, &pStream) == S_OK)
{
HRESULT hr;
if(E_NOINTERFACE == (hr = OleLoadPicture(pStream, nSize, FALSE, IID_IPicture, (LPVOID *)&p_IPicture)))
{
return(FALSE);
}
else // S_OK
{
pStream->Release();
pStream = NULL;
}
}
// MSDN:not necessary for Win32-based applications
UnlockResource(hGlobal);
FreeResource(hGlobal);
FreeResource(hGlobalMem);
// 4.得到图像句柄,拷贝
if(p_IPicture != NULL)
{
// Get the handle to the image, and then copy it.
if((p_IPicture->get_Handle(&hJpegBmp)) != S_OK)
{
p_IPicture->Release();
p_IPicture = NULL;
*lphBmp = 0;
return(FALSE);
}
if((*lphBmp = (HBITMAP)CopyImage((HANDLE *) hJpegBmp, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG)) == NULL)
{
p_IPicture->Release();
p_IPicture = NULL;
*lphBmp = 0;
return(FALSE);
}
p_IPicture->Release();
p_IPicture = NULL;
return(TRUE);
}
else
{
p_IPicture->Release();
p_IPicture = NULL;
return(FALSE);
}
} |