Loading PNG (and JPG) image from resource using GDI+

Last night while I was translating some of my old animation program from GDI32 to GDI+, I’ve hit a roadblock where GDI+ cannot load PNG (and JPEG) file stored as resource: 

// This code doesn't work
Gdiplus::Bitmap* m_image = Gdiplus::Bitmap::FromResource(hInst, L"IDB_IMAGE1");

I’m thinking of an alternative using Bitmap::FromStream / FindResource / LoadResource combo, but I have one problem, I’m not familiar with Bitmap::FromStream. So I’ve checked CodeProject for some sample code on how to use Bitmap::FromStream, this I think will be a good start at what I want to do.

While I was searching for sample code, I’ve bumped on an article posted by Joe Woodbury entitled Loading JPG & PNG resources using GDI+ (glad I’ve searched CodeProject before going to MSDN). This article and the demo source code is exactly what I need, so I figure I will write a sample program using his CGdiPlusBitmapResource to test it.

Just to make things quicker and smaller, I’ve used David Nash's Win++ for this sample program:

The class CGdiPlusBitmapResource doesn’t need any documentation., all you have to do is create an instance of this class., and call it’s Load function and you’re technically done:

CGdiPlusBitmapResource* m_image = new CGdiPlusBitmapResource();
m_image->Load(IDB_IMAGE, _T("PNG"), hInst);

 

And draw it using Graphics object:

// Create graphics object from HDC
Gdiplus::Graphics g(hDC);

// Draw the PNG image using graohics object
g.DrawImage(*m_image, 0, 0);

 


That’s about it. Then you can delete the m_image when you’re done using it.
Check attached sample program for a working demo. It contains Win++ for writing C++ Win32 application, and CGdiPlusBitmap.h header file for loading images from resources.

If you want to know more about GDI+, here' a good article: Starting with GDI+

Published 07-28-2008 5:49 AM by cvega
Filed under: ,

Comments

# re: Loading PNG (and JPG) image from resource using GDI+

Wednesday, July 30, 2008 1:57 AM by modchip

Looks complicated... have you by any chance something like this but in MASM32? :D

# re: Loading PNG (and JPG) image from resource using GDI+

Thursday, July 31, 2008 12:24 AM by cvega

Yes., there is the PNGLib from MadWizard created by Thomas :)

www.madwizard.org/.../pnglib

Simply use PNG_LoadResource to load PNG file from resource.