Skip to content

Instantly share code, notes, and snippets.

@evpobr
Created October 12, 2015 17:35
Show Gist options
  • Save evpobr/87aa1728af3f2cfc0911 to your computer and use it in GitHub Desktop.
Save evpobr/87aa1728af3f2cfc0911 to your computer and use it in GitHub Desktop.
Load 32-bit PNG from resource
HBITMAP LoadPng(HINSTANCE hInstance, LPCWSTR lpBitmapName)
{
HBITMAP hbmp = nullptr;
HRSRC hResInfo = FindResourceW(hInstance, lpBitmapName, L"PNG");
if (hResInfo)
{
DWORD dwSize = SizeofResource(hInstance, hResInfo);
if (dwSize)
{
HGLOBAL hResData = LoadResource(hInstance, hResInfo);
if (hResData)
{
LPVOID pImageData = LockResource(hResData);
if (pImageData)
{
IWICImagingFactoryPtr pWICImagingFactory;
HRESULT hr = pWICImagingFactory.CreateInstance(CLSID_WICImagingFactory);
if (SUCCEEDED(hr))
{
IWICStreamPtr pStream;
hr = pWICImagingFactory->CreateStream(&pStream);
if (SUCCEEDED(hr))
{
hr = pStream->InitializeFromMemory(reinterpret_cast<BYTE*>(pImageData), dwSize);
if (SUCCEEDED(hr))
{
IWICBitmapDecoderPtr pDecoder;
hr = pWICImagingFactory->CreateDecoderFromStream(pStream, nullptr, WICDecodeMetadataCacheOnLoad, &pDecoder);
if (SUCCEEDED(hr))
{
IWICBitmapFrameDecodePtr pSource;
hr = pDecoder->GetFrame(0, &pSource);
if (SUCCEEDED(pSource))
{
IWICBitmapSourcePtr pDest = nullptr;
hr = WICConvertBitmapSource(GUID_WICPixelFormat32bppPBGRA, pSource, &pDest);
if (SUCCEEDED(hr))
{
UINT uiWidth, uiHeight;
hr = pDest->GetSize(&uiWidth, &uiHeight);
if (SUCCEEDED(hr))
{
BITMAPINFO bminfo;
ZeroMemory(&bminfo, sizeof(bminfo));
bminfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bminfo.bmiHeader.biWidth = uiWidth;
bminfo.bmiHeader.biHeight = -((LONG)uiHeight);
bminfo.bmiHeader.biPlanes = 1;
bminfo.bmiHeader.biBitCount = 32;
bminfo.bmiHeader.biCompression = BI_RGB;
LPVOID pvImageBits = nullptr;
HDC hdcScreen = GetDC(nullptr);
hbmp = CreateDIBSection(hdcScreen, &bminfo, DIB_RGB_COLORS, &pvImageBits, NULL, 0);
ReleaseDC(nullptr, hdcScreen);
if (hbmp)
{
UINT cbStride = uiWidth * 4;
const UINT cbImage = cbStride * uiHeight;
hr = pDest->CopyPixels(nullptr, cbStride, cbImage, static_cast<BYTE *>(pvImageBits));
if (SUCCEEDED(hr))
return hbmp;
}
}
}
}
}
}
}
}
}
}
}
}
return hbmp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment