Search code examples
c++visual-studiomfcpng

How to load a png resource into picture control on a dialog box?


I tried the following code on OnInitDialog() but nothing was shown.

m_staticLogo.SetBitmap(::LoadBitmap(NULL, MAKEINTRESOURCE(IDB_LOGO)));

where m_staticLogo is the static picture control and IDB_LOGO is the resource ID of the png file.


Solution

  • As you’ve discovered, ::LoadBitmap (and the newer ::LoadImage) only deal with .bmps. By far the easiest solution is to convert your image to a .bmp.

    If the image has transparency, it can be converted into a 32-bit ARGB bitmap (here is a tool called AlphaConv that can convert it). Then load the image using the CImage class LoadFromResource method. Pass the CImage to m_staticLogo.SetBitmap().

    But if you really need it to be a .png, it can be done.

    Method 1 (the easier way): Load the .png from a file using CImage::Load. Pass the CImage to m_staticLogo.SetBitmap().

    Method 2 (the harder way): Load the .png from a resource by loading the resource into a COM IStream and using CImage::Load. (NOTE: CImage::LoadFromResource looks tempting but will not work with a .png graphic). To get the resource into a COM IStream, see this Codeproject article. Note the article works with Gdiplus::Bitmap but the key part is how to create the IStream, which you should be able to adapt for CImage. Finally, pass the CImage to m_staticLogo.SetBitmap().

    Edit: Updated to use CImage, which is easier than Gdiplus::Bitmap.