很多时候我们习惯使用GDI+中Image类来加载本地文件,但是有时候我们需要资源中从加载png格式的图片时,却无法使用该类。
我们可以使用FindResource,LoadResource和LockResource以获取指向图像字节的指针。然后从中创建一个IStream。IStream可用于初始化GDI +图像或位图对象。
在.rc文件中添加新行:
IDI_MY_IMAGE_FILE PNG "foo.png"
并确保在resource.h头文件中将IDI_MY_IMAGE_FILE定义为整数。
#define IDI_MY_IMAGE_FILE 131
然后在运行时加载图像:
Gdiplus::Bitmap* pBmp = LoadImageFromResource(hInstance, MAKEINTRESOURCE(IDI_MY_IMAGE_FILE), L"PNG");
LoadImageFromResource的代码如下:
Gdiplus::Bitmap* LoadImageFromResource(HMODULE hMod, const wchar_t* resid, const wchar_t* restype) { IStream* pStream = nullptr; Gdiplus::Bitmap* pBmp = nullptr; HGLOBAL hGlobal = nullptr; HRSRC hrsrc = FindResourceW(hInst, resid, restype); // get the handle to the resource if (hrsrc) { DWORD dwResourceSize = SizeofResource(hMod, hrsrc); if (dwResourceSize > 0) { HGLOBAL hGlobalResource = LoadResource(hMod, hrsrc); // load it if (hGlobalResource) { void* imagebytes = LockResource(hGlobalResource); // get a pointer to the file bytes // copy image bytes into a real hglobal memory handle hGlobal = ::GlobalAlloc(GHND, dwResourceSize); if (hGlobal) { void* pBuffer = ::GlobalLock(hGlobal); if (pBuffer) { memcpy(pBuffer, imagebytes, dwResourceSize); HRESULT hr = CreateStreamOnHGlobal(hGlobal, TRUE, &pStream); if (SUCCEEDED(hr)) { // pStream now owns the global handle and will invoke GlobalFree on release hGlobal = nullptr; pBmp = new Gdiplus::Bitmap(pStream); } } } } } } if (pStream) { pStream->Release(); pStream = nullptr; } if (hGlobal) { GlobalFree(hGlobal); } return pBmp; }
相关链接: C ++ GDI +如何从资源获取和加载图像?