從資源中加載jpg和png文件, 貌似不應(yīng)該是個(gè)大問題, 一google結(jié)果一大堆, 卻有兩個(gè)陷阱,trap啊
1, 是Bitmap(RT_BITMAP)類型的圖片無法加載, RT_BITMAP是預(yù)定義類型, 資源里面沒有bmp文件的頭,
SizeofResource 的返回值要比圖片文件少幾個(gè)字節(jié),因?yàn)樯倭诉@幾個(gè)字節(jié), 所以GDI+會(huì)返回invalid parameter錯(cuò)誤。
2, 從
IStream里面創(chuàng)建出來的Image對象似乎會(huì)引用到堆里面的內(nèi)存, 如果
hBuffer被釋放了, 創(chuàng)建的Image的內(nèi)容就會(huì)被破壞,有時(shí)只能畫出一小部分圖片, 有時(shí)整個(gè)圖片就是空白, 視當(dāng)時(shí)的內(nèi)存狀況而定。調(diào)用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);
}