GDI+ 从资源文件读取自定义图片

BOOL ImageFromIDResource(UINT nID, LPCTSTR sTR, Image * & pImg)
{
	HINSTANCE hInst = AfxGetResourceHandle();
	HRSRC hRsrc = ::FindResource (hInst,MAKEINTRESOURCE(nID),sTR); // type
	if (!hRsrc)
		return FALSE;
	// load resource into memory
	DWORD len = SizeofResource(hInst, hRsrc);
	BYTE* lpRsrc = (BYTE*)LoadResource(hInst, hRsrc);
	if (!lpRsrc)
		return FALSE;
	// Allocate global memory on which to create stream
	HGLOBAL m_hMem = GlobalAlloc(GMEM_FIXED, len);
	BYTE* pmem = (BYTE*)GlobalLock(m_hMem);
	memcpy(pmem,lpRsrc,len);
	IStream* pstm;
	CreateStreamOnHGlobal(m_hMem,FALSE,&pstm);
	// load from stream
	pImg=Gdiplus::Image::FromStream(pstm);
	// free/release stuff
	GlobalUnlock(m_hMem);
	pstm->Release();
	FreeResource(lpRsrc);
	return TRUE;
}

调用方法:

Graphics graphics( GetDC()->m_hDC);   
	Image *pImage = NULL;
	ImageFromIDResource(IDB_SHOW,_T("PNG"),pImage);  
	graphics.DrawImage(pImage,250, 60,pImage->GetWidth(),pImage->GetHeight());  //绘制背景
	delete pImage;//记得要释放

 

你可能感兴趣的:(C++,MFC)