从资源中加载jpg和png文件, 貌似不应该是个大问题, 一google结果一大堆, 却有两个陷阱,trap啊
1, 是Bitmap(RT_BITMAP)类型的图片无法加载, RT_BITMAP是预定义类型, 资源里面没有bmp文件的头,
SizeofResource 的返回值要比图片文件少几个字节,因为少了这几个字节, 所以GDI+会返回invalid parameter错误。
2, 从
IStream里面创建出来的Image对象似乎会引用到堆里面的内存, 如果
hBuffer被释放了, 创建的Image的内容就会被破坏,有时只能画出一小部分图片, 有时整个图片就是空白, 视当时的内存状况而定。调用Image的Clone也没用。
CYourClass::~CYourClass()
{
for(IMG_VECTOR::iterator it = m_arImage.begin(); it != m_arImage.end(); it++)
delete *it;
for(HGLB_VECTOR::iterator it = m_arGlobal.begin(); it != m_arGlobal.end(); it++)
{
::GlobalUnlock(*it);
::GlobalFree(*it);
}
}
void CYourClass::AddImage(HMODULE hInst, UINT nResourceID, LPCTSTR lpType)
{
if(lpType == RT_BITMAP)
{
//GDI+ can not load RT_BITMAP resouce,
//because they are predefined resource,
//they don't contains the image file header.
assert(FALSE);
return;
}
HRSRC hResource = ::FindResource(hInst, MAKEINTRESOURCE(nResourceID), lpType);
if (!hResource)
return;
DWORD imageSize = ::SizeofResource(hInst, hResource);
if (!imageSize)
return;
const void* pResourceData = ::LockResource(::LoadResource(hInst, hResource));
if (!pResourceData)
return;
HGLOBAL hBuffer = ::GlobalAlloc(GMEM_FIXED, imageSize);
if (NULL == hBuffer)
return;
void* pBuffer = ::GlobalLock(hBuffer);
if (pBuffer)
{
CopyMemory(pBuffer, pResourceData, imageSize);
IStream* pStream = NULL;
if (::CreateStreamOnHGlobal(hBuffer, FALSE, &pStream) == S_OK)
{
Gdiplus::Image * pImage = Gdiplus::Image::FromStream(pStream);
pStream->Release();
if (pImage)
{
if (pImage->GetLastStatus() == Gdiplus::Ok &&
pImage->GetWidth() > 0)
{
m_arImage.push_back(pImage);
//it seems the image will take usage of the global memory.
//so the global memory should be kept until the image destroy.
m_arGlobal.push_back(hBuffer);
return;
}
delete pImage;
}
}
::GlobalUnlock(hBuffer);
}
::GlobalFree(hBuffer);
}