Click here to Skip to main content
Click here to Skip to main content

Loading JPG & PNG resources using GDI+

, 6 Sep 2004
Rate this:
Please Sign up or sign in to vote.
A class to facilitate loading JPG and PNG files from resources using GDI+

Introduction

Recently, I needed to display some JPG and PNG files. I had an old copy of LeadTools and the open source libraries for both formats, but wanted my executable to be as small as possible. So I decided to give GDI+ a try. I quickly found GDI+ to be poorly designed and very quirky, but it worked well for my purposes until I discovered, to my horror, that GDI+ cannot load JPG or PNG images stored as resources!

Like, I'm sure, other developers facing this issue, I disbelieved the documentation and tried Bitmap::FromResource to no avail. While perusing the Bitmap methods available, I ran across Bitmap::FromStream.

After a bit of testing and several errors, due mostly to the horrible GDI+ documentation, I came up with working code. After a night of rest, I decided to encapsulate the code in a simple class to ensure memory got freed. The result were two classes: CGdiPlusBitmap and CGdiPlusBitmapResource.

The Gotcha

Before discussing the code itself, there is a caveat with GDI+ that must be addressed. With JPG, some TIFF and other formats, the original image information must be available at all times. In other words, if you open a bitmap using Bitmap::FromFile, you cannot delete or otherwise change that file while the image is open. This same restriction applies to CGdiPlusBitmapResource. (My testing found that PNG and BMP files don't seem to follow this generalization, though I don't know if this is standard behavior or just a fluke with my file set.)

GDI+ Initialization

GDI+ needs to be initialized before any GDI+ calls are made. I suggest adding the following data member to the class derived from CWinApp:

ULONG_PTR m_gdiplusToken;

In InitInstance(), add the following calls:

Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);

In ExitInstance(), add the following:

Gdiplus::GdiplusShutdown(m_gdiplusToken);

The Class

I created two classes, with the base class being a very simple encapsulation of Bitmap and the derived class encapsulating the global memory. I suppose that if I ever had the patience and desire, I could extend that class, but I have no need to do so. (If you're curious why I didn't simply derive from the ATL class CImage, it's because the code was used in a program that didn't use MFC or ATL. However, the code is so simple, it could easily be modified to use CImage as the base class.)

I'm not going to bother going over the CGdiPlusBitmap class except to say that it has a single, public, data member Bitmap* m_pBitmap. (In the class I prefaced the GDI+ objects with the Gdiplus namespace in case the developer doesn't want to declare using namespace Gdiplus;.)

The CGdiPlusBitmapResource class has several constructors and several overloaded Load functions. The overloaded functions simply allow lazy programmers, like myself, to not have to type MAKEINTRESOURCE. The main Load function takes the resource name and type as strings and is the key to the class. This code follows in its entirety:

inline
bool CGdiPlusBitmapResource::Load(LPCTSTR pName, LPCTSTR pType, 
                                  HMODULE hInst)
{
    Empty();

    HRSRC hResource = ::FindResource(hInst, pName, pType);
    if (!hResource)
        return false;
    
    DWORD imageSize = ::SizeofResource(hInst, hResource);
    if (!imageSize)
        return false;

    const void* pResourceData = ::LockResource(::LoadResource(hInst, 
                                              hResource));
    if (!pResourceData)
        return false;

    m_hBuffer  = ::GlobalAlloc(GMEM_MOVEABLE, imageSize);
    if (m_hBuffer)
    {
        void* pBuffer = ::GlobalLock(m_hBuffer);
        if (pBuffer)
        {
            CopyMemory(pBuffer, pResourceData, imageSize);

            IStream* pStream = NULL;
            if (::CreateStreamOnHGlobal(m_hBuffer, FALSE, &pStream) == S_OK)
            {
                m_pBitmap = Gdiplus::Bitmap::FromStream(pStream);
                pStream->Release();
        if (m_pBitmap)
        { 
          if (m_pBitmap->GetLastStatus() == Gdiplus::Ok)
            return true;

          delete m_pBitmap;
          m_pBitmap = NULL;
        }
            }
            m_pBitmap = NULL;
            ::GlobalUnlock(m_hBuffer);
        }
        ::GlobalFree(m_hBuffer);
        m_hBuffer = NULL;
    }
    return false;
}

I find the code very self explanatory, though those that know the return value of ::LoadResource is an HGLOBAL may find the apparent double copy using CopyMemory confusing. In brief CreateStreamOnHGlobal requires a HGLOBAL handle allocated by GlobalAlloc using the GMEM_MOVEABLE flag.

The Demo

The demo is a Visual Studio .NET 2003 project with ANSI and UNICODE builds. It allows you to load resampled JPG or PNG resources (For the curious, I took both photographs in Oahu, Hawaii for, and while filming content of, a multimedia product. One is of Laie Bay, the other is a sunset viewed from Waikiki.)

GDI+ Disclaimer

I am not a GDI+ expert, nor am I a big fan, even if I do find GDI+ occasionally very useful. Please don't ask me questions about it.

Why not IPicture?

I've been asked why I didn't use IPicture. The answer is threefold; first, IPicture does not support PNG images. Second, IPicture is pretty much only an image loader, with little more capability than the standard GDI bitmap calls. Third, IPicture decodes the image data immediately. JPG and GIF images will use more memory than this class.

Updates

22 April 2004

CreateStreamOnHGlobal now uses FALSE for the second argument since Bitmap requires that the memory be retained for at least JPG images and I decided to err on the side of caution. Interestingly, my testing showed this flag is often ignored, but I received reports that this wasn't always the case and was technically incorrect.

In addition, while fixing this bug I realized I wasn't clearing up the global memory on failure. That resulted in the code being rearranged as it is now.

15 June 2004

If Gdiplus::Bitmap::FromStream fails, I added what I believe is redundant, but more correct code in handling m_pBitmap. (Unfortunately, the documentation is silent on the subject as to whether NULL will always be returned on failure.)

3 September 2004

Added a section on GDI+ initialization.

Fixed a potential memory leak on image load failure in the sample application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Joe Woodbury
Software Developer (Senior)
United States United States
Joe is one of those software engineers with a film degree. His first paid programming job (what, you think film is a good way to make a living?) was writing games for Apple II's using 6502 assembly. He soon moved to 80x86 assembly, C then C++ for a long time and finally, C#/.NET.
 
He first wrote software for Windows 3.0 in 1990, when it was first released. Save for some continued work in DOS and a horid, and mercifully brief, foray into OS/2, he has concentrated on designing and writing Windows applications, libraries and middleware, whatever that is.
Follow on   LinkedIn

Comments and Discussions

 
Questionabout free the HGLOBAL variable m_hBuffer Pinmemberkoll Zhu23-Jul-14 22:17 
AnswerRe: about free the HGLOBAL variable m_hBuffer PinprofessionalJoe Woodbury24-Jul-14 4:03 
BugSlight error in CGdiPlusBitmapResource::Load (location of the call to GlobalUnlock) + suggested fix Pinmemberjoel vibert17-Jul-14 1:14 
GeneralRe: Slight error in CGdiPlusBitmapResource::Load (location of the call to GlobalUnlock) + suggested fix PinprofessionalJoe Woodbury17-Jul-14 6:45 
QuestionVisual Studio Express usage note PinmemberDavid O'Neil11-Feb-14 5:07 
QuestionHow do I use this? PinmemberMember 1042229723-Nov-13 23:34 
AnswerRe: How do I use this? PinprofessionalJoe Woodbury24-Nov-13 6:16 
GeneralRe: How do I use this? [modified] PinmemberMember 1042229725-Nov-13 6:02 
GeneralRe: How do I use this? PinprofessionalJoe Woodbury25-Nov-13 6:55 
GeneralRe: How do I use this? PinmemberMember 1042229725-Nov-13 8:06 
GeneralRe: How do I use this? PinprofessionalJoe Woodbury25-Nov-13 8:34 
GeneralRe: How do I use this? PinmemberMember 1042229725-Nov-13 9:23 
GeneralRe: How do I use this? PinprofessionalJoe Woodbury25-Nov-13 9:57 
GeneralRe: How do I use this? PinmemberJoeMut26-Nov-13 2:19 
GeneralRe: How do I use this? PinprofessionalJoe Woodbury26-Nov-13 4:05 
SuggestionRe: How do I use this? PinmemberJoeMut26-Nov-13 4:46 
QuestionMessage Automatically Removed PinmemberThisIsANameOK3-Nov-13 12:50 
AnswerRe: Holy moly. This is sloppy code with memory leaks to boot. Pinmemberenhzflep20-Nov-13 22:39 
GeneralMessage Automatically Removed PinmemberThisIsANameOK30-Dec-13 12:35 
GeneralRe: Holy moly. This is sloppy code with memory leaks to boot. [modified] PinprofessionalJoe Woodbury30-Dec-13 15:26 
GeneralMy vote of 5 Pinmemberbb232320-Aug-12 13:29 
QuestionCrashes on XP PinmemberThomas Williams7-Aug-12 8:38 
AnswerRe: Crashes on XP PinmemberJoe Woodbury7-Aug-12 8:46 
GeneralRe: Crashes on XP PinmemberThomas Williams7-Aug-12 8:59 
GeneralMy vote of 3 Pinmemberhoseinhero18-Jun-12 3:22 
GeneralMy vote of 5 Pinmembermanoj kumar choubey16-Feb-12 23:56 
QuestionCImage Pinmembermeerius19-Jan-12 8:28 
AnswerRe: CImage PinmemberJoe Woodbury19-Jan-12 9:21 
GeneralRe: CImage Pinmembermeerius20-Jan-12 2:31 
GeneralExcellent! PinmemberYoSilver10-Aug-11 5:56 
GeneralLockfree File loading. PinmemberOBWANDO10-May-11 4:45 
GeneralRe: Lockfree File loading. PinmemberJoe Woodbury10-May-11 5:33 
GeneralVery useful article and sample code PinmemberPhilippe Marechal7-May-11 10:22 
GeneralRe: Very useful article and sample code PinmemberJoe Woodbury7-May-11 12:02 
GeneralVS2010 [modified] PinmemberMr Crisp10-Feb-11 22:45 
GeneralRe: VS2010 PinmemberJoe Woodbury11-Feb-11 5:30 
GeneralRe: VS2010 PinmemberMr Crisp12-Feb-11 3:30 
QuestionDisplaying loaded PNG with transparent background color Pinmembermasteryoda2127-Jan-11 11:28 
This article is great and I've gotten the code to work (in VS 2010), and this question may be a little off the topic, but:
 
Once I've loaded a PNG from the resource file:
 
          CGdiPlusBitmapResource* pBitmap = new CGdiPlusBitmapResource;
          if (pBitmap->Load(IDB_PNG , _T("PNG")))
 
How do I display that image, pBitmap, with a transparent background color?   For example: say I want all black (RGB(0,0,0)) pixels or magenta (RGB(255,0,255)) pixels to be transparent so the background shows through, is there a way to display pBitmap (a png) so that a certain pixel displays transparent?
AnswerRe: Displaying loaded PNG with transparent background color PinmemberJoe Woodbury27-Jan-11 16:03 
GeneralRe: Displaying loaded PNG with transparent background color Pinmembermasteryoda2127-Jan-11 16:24 
GeneralRe: Displaying loaded PNG with transparent background color PinmemberJoe Woodbury27-Jan-11 16:47 
GeneralRe: Displaying loaded PNG with transparent background color [modified] PinmemberCoruscant17-Jul-12 2:05 
GeneralRe: Displaying loaded PNG with transparent background color PinmemberMember 568844324-Apr-14 1:41 
QuestionHow to repaint the png image PinmemberDJangra24-Oct-10 21:36 
AnswerRe: How to repaint the png image PinmemberJoe Woodbury25-Oct-10 5:47 
GeneralBUG: Do not free the global memory block before returning! Pinmemberdc_200018-Oct-10 12:18 
GeneralRe: BUG: Do not free the global memory block before returning! PinmemberJoe Woodbury18-Oct-10 12:43 
GeneralRe: BUG: Do not free the global memory block before returning! Pinmemberdc_200019-Oct-10 7:45 
GeneralRe: BUG: Do not free the global memory block before returning! PinmemberJoe Woodbury19-Oct-10 11:33 
GeneralMy vote of 5 Pinmemberanna.novikova1-Oct-10 7:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 7 Sep 2004
Article Copyright 2003 by Joe Woodbury
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid