none
How to dispose BitmapSource?

    Question

  • Hi all,

    How can I dispose BitmapSource (actually InteropBitmapSource)? 

    Example of memory leak:

     

                while (true)

                {

                    using (Bitmap bitmap = new Bitmap(1000, 1000))

                    {

                        BitmapSource source = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),

                            IntPtr.Zero, new Int32Rect(0, 0, bitmap.Width, bitmap.Height),

                            BitmapSizeOptions.FromEmptyOptions());

                    }

                    GC.Collect();

                    Console.Read();

                }

     

    Thanks for any hints.

     

    Tom

    Monday, July 03, 2006 10:17 AM

Answers

  • When you call GetHbitmap you are responsible for calling DeleteObject to free its memory

     

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);
    
           
    private void DemonstrateGetHbitmap() 
    {
        Bitmap bm = new Bitmap("Picture.jpg");
        IntPtr hBitmap = bm.GetHbitmap();
                 
        // Do something with hBitmap.
        DeleteObject(hBitmap);
    }
    
    Tuesday, July 25, 2006 7:09 PM

All replies

  • did you figure this out?  I'm having the exact same issue right now
    Tuesday, July 25, 2006 4:18 PM
  • When you call GetHbitmap you are responsible for calling DeleteObject to free its memory

     

    [System.Runtime.InteropServices.DllImport("gdi32.dll")]
    public static extern bool DeleteObject(IntPtr hObject);
    
           
    private void DemonstrateGetHbitmap() 
    {
        Bitmap bm = new Bitmap("Picture.jpg");
        IntPtr hBitmap = bm.GetHbitmap();
                 
        // Do something with hBitmap.
        DeleteObject(hBitmap);
    }
    
    Tuesday, July 25, 2006 7:09 PM
  • This is spot on.
    Tuesday, July 25, 2006 8:08 PM
  • Forgot to mention that the information (and code sample) was taken from the documentation for GetHbitmap.
    Wednesday, July 26, 2006 12:56 AM
  • Ok. Thanks. I did not check the documentation for Bitmap.GetHbitmap(), I just used IntelliSense:)
    Wednesday, September 20, 2006 8:19 PM
  • Whoops, CreateBitmapSourceFromHBitmap create copy of HBitmap?
    Tuesday, May 29, 2007 3:32 PM
  • I know that this post is old, but, actually, there is an easier way to do this operation. So, I'll just drop the code here for reference:

    Bitmap bitmap = (Bitmap)value;
    MemoryStream bitmapStream = new MemoryStream();
    BitmapSource bitmapSource = null;
    bitmap.Save(bitmapStream, ImageFormat.Bmp);
    bitmapSource = BitmapFrame.Create(bitmapStream);
    
    
    Friday, April 01, 2011 1:21 AM