tags:

views:

551

answers:

3

I am trying to load a non-bmp image (png in my case) into a Bitmap/Image instance from a resource in my app. Since the Bitmap constructor only has an overload for a bitmap resource, this is what i've came around:

I allocate memory on the global heap, and then copy the resource data into it. Then I create an IStream for that global memory block (using CreateStreamOnHGlobal) and use the Image/Bitmap constructor that takes that stream. Basically it works, although i am not sure that this is the best way to do it: I've noticed that if I free that memory block after creating the image, it wouldn't be drawn (Calling DrawImage won't produce anything). Which raises two questions:

  1. How do I manage the lifetime of that memory block? I doubt it would get deallocated upon the image's destruction.

  2. Does the Image/Bitmap class uses the png data in it's compressed form and translates it into raw data on each call to DrawImage? Seems very unefficient.

Any sugestions?

A: 

Convert the Bitmap to CachedBitmap then get rid of the memory.

Shay Erlichmen
The problem with CachedBitmap, is that it doesn't inherit from Image, so it needs to be treated differently than "regular" bitmaps.I've managed to solve the memory lifetime problem, fortunatlly Image has a virtual distructor, so it's quite simple. Yet, I am still not sure that this is the right way to go.
Meat
I think that if Bitmap saved a copy of the data uncompress, then a lot of ppl would jump and say that it not very efficient also (memory wise).
Shay Erlichmen
+2  A: 

When using non bitmap resources I have based my code on that from codeproject.

IStream* pStream = NULL;
::CreateStreamOnHGlobal(m_hBuffer, FALSE, &pStream)
m_pBitmap = Gdiplus::Bitmap::FromStream(pStream);
pStream->Release();

Looking at that code once you do a from stream to create the bitmap then you call Release() on the stream to remove your reference count on the stream, thereby tying the lifetime of the stream to the Bitmap.

Then you can use whatever mechanism you wish to manage that pointer.

JProgrammer
A: 

> I have based my code on that from codeproject.

It's not 'from codeproject". It's from MSDN (as always...)