Releasing the memory used when drawing a Bitmap

  • Thread starter Thread starter =?ISO-8859-1?Q?Mikko_Nyl=E9n?=
  • Start date Start date
?

=?ISO-8859-1?Q?Mikko_Nyl=E9n?=

Is there a way to release the memory used while drawing a Bitmap using
Graphics.DrawImage?

The code I use:

--
....
using (Image im = Image.FromHbitmap(map.GetHbitmap()) {
g.DrawImage(im, 0, 0);
}
--

where "map" is an instance of Bitmap and "g" is instance of Graphics.

Now every time I draw the image, the memory usage increases by 0,5 MB
and doesn't decrease after it. It is a problem, because I must draw the
same Bitmap very often. A bit of moving mouse and Task Manager reports
that application is using over 300 MB of memory.

Minimizing the window and then maximizing it helps, but because I'm not
doing this for only myself, it's not a solution.

The solutions I have tried:

- call Graphics.Dispose() and recreate the Graphics object
before/after each redraw
- call Graphics.Clear before/after each redraw
- call System.GC.Collect() before/after each redraw

None of the solutions listed above haven't helped in any way.

- Mikko Nylén
 
I don't understand why you're using Image.FromHBitmap(map.GetHBitmap())
which is round-tripping a bitmap creation every time you draw rather than
simply using DrawImage(map,0,0). Is this you misunderstanding the usage or
is there some other devious plan at work here?

If the plan is indeed devious you might like to dispose of im occasionally
to free up it's memory.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Bob said:
I don't understand why you're using Image.FromHBitmap(map.GetHBitmap())
which is round-tripping a bitmap creation every time you draw rather than
simply using DrawImage(map,0,0). Is this you misunderstanding the usage or
is there some other devious plan at work here?

If the plan is indeed devious you might like to dispose of im occasionally
to free up it's memory.

I have been pulling off my hairs for whole day because of this. And why?
Because I didn't look at Bitmap's inheritance three so closely! I really
didn't know that Bitmap inherits from Image and therefore I used
Image.FromHBitmap(map.GetHBitmap()).

But anyway, thanks a lot! That solved the problem and now the memory
usage stays fair.

- Mikko Nylén
 
Back
Top