extracrispy
extracrispy

Reputation: 679

GDI+ GetHBITMAP memory error?

So I was trying to learn some GDI basics and my code breaks when I try to get the HBITMAP for a png image I want to display...

HBITMAP SplashScreen::LoadPng(WCHAR* path)
{
  HBITMAP bmp;
  fstream f;
  f.open(path);
  if(!f.good())
  {
    throw std::exception("Can't find/read file.");
  }
  f.close();

  Gdiplus::Bitmap* img = Gdiplus::Bitmap::FromFile(path, FALSE); 
  Gdiplus::Color bg(0,0,0,0); 
  img->GetHBITMAP(bg, &bmp);     // <--- Breaks here! Memory access exception!

  return bmp;
}

The code is already so simple, I can't think of anything wrong with it, except maybe I just didn't set something up beforehand??

Thoughts?

Upvotes: 0

Views: 2173

Answers (2)

extracrispy
extracrispy

Reputation: 679

I didn't initialize GDI correctly. After fixing my init code, it works fine. That was annoying. Now I know.

Upvotes: 0

enhzflep
enhzflep

Reputation: 13089

Not sure what your problem is, though, I do note that you've got a memory leak. img is never deleted - you should call delete img; after the call to GetHBITMAP

I use the following (less thorough code) in quick test projects.

// BMP, GIF, JPEG, PNG, TIFF, Exif, WMF, and EMF
HBITMAP mLoadImg(WCHAR *szFilename)
{
   HBITMAP result=NULL;

   Gdiplus::Bitmap* bitmap = new Gdiplus::Bitmap(szFilename,false);
   bitmap->GetHBITMAP(0, &result);
   delete bitmap;
   return result;
}

Upvotes: 2

Related Questions