tags:

views:

48

answers:

2

How do i load a png resource into a CBitMap? When i try this it doesnt work.

CImage image;
image.LoadFromResource(AfxGetInstanceHandle(), IDB_PNG1);
bitmap.Attach(image.Detach());

It gives me an error resource type not found. Is there any other way to load a PNG resource?

A: 

LoadFromResource uses LoadImage internally, it doesn't support PNG last time I tried, despite what the documentation says. You can link with CxImage (look on codeproject) but it's a lot of work for little real benefit.

What I did in the end was forget about PNG, use AlphaConv to convert PNG's into 32-bit Windows bitmaps and use CImage with those. Additional advantage is that you can use them with CBitmapButton etc. in MFC without any transformations.

Another way to hack around it is to extract the resource contents to a temporary file, then use CImage::Load to read it from there. If I'd catch you doing that in one of my code bases I'd punch you in the face though ;)

Roel
A: 

Use a library like CxImage (http://www.xdp.it/cximage.htm) to do all the heavy lifting for you. The code becomes as simple as :-

CxImage image;
if (image.LoadResource(<resource_instance_handle>, <resource_id>, CXIMAGETYPE_PNG))
{
    HBITMAP hbmp = image.CreateHBITMAP();
    ... do something with hbmp ...
}

(note that I'm writing this code from memory -- you may need to tweak it slightly to get it to work!)

I use CxImage a lot for the graphics in my programs and it simplifies things tremendously.

Darren Ford