一、 实现代码
void DrawImage(HDC hdc,RECT& rc,UINT nIDResource,CString lpType)
{
HINSTANCE hInst = AfxGetResourceHandle();
HRSRC hRsrc = ::FindResource(hInst, MAKEINTRESOURCE(nIDResource), lpType);
if (!hRsrc)
return;
//资源大小
DWORD len = SizeofResource(hInst, hRsrc);
//转换图片资源为字节数组
BYTE* lpRsrc = (BYTE*)LoadResource(hInst, hRsrc);
if (!lpRsrc)
return;
IImagingFactory *pImgFactory = NULL;
IImage *pImage = NULL;
CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (SUCCEEDED(CoCreateInstance (CLSID_ImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IImagingFactory,
(void **)&pImgFactory)))
{
if (SUCCEEDED(pImgFactory->CreateImageFromBuffer(lpRsrc,len,BufferDisposalFlagNone,&pImage)))
{
pImage->Draw(hdc, &rc, NULL);
pImage->Release();
}
pImgFactory->Release();
}
CoUninitialize();
//释放资源
FreeResource(hRsrc);
}
{
HINSTANCE hInst = AfxGetResourceHandle();
HRSRC hRsrc = ::FindResource(hInst, MAKEINTRESOURCE(nIDResource), lpType);
if (!hRsrc)
return;
//资源大小
DWORD len = SizeofResource(hInst, hRsrc);
//转换图片资源为字节数组
BYTE* lpRsrc = (BYTE*)LoadResource(hInst, hRsrc);
if (!lpRsrc)
return;
IImagingFactory *pImgFactory = NULL;
IImage *pImage = NULL;
CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (SUCCEEDED(CoCreateInstance (CLSID_ImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IImagingFactory,
(void **)&pImgFactory)))
{
if (SUCCEEDED(pImgFactory->CreateImageFromBuffer(lpRsrc,len,BufferDisposalFlagNone,&pImage)))
{
pImage->Draw(hdc, &rc, NULL);
pImage->Release();
}
pImgFactory->Release();
}
CoUninitialize();
//释放资源
FreeResource(hRsrc);
}
代码说明:
a). 关键部分为将LoadResource转换成BYTE*以及CreateImageFromBuffer方法。
本文转自博客园农民伯伯的博客,原文链接:[WM C++]从资源文件中加载显示png/jpg图片,如需转载请自行联系原博主。