BitmapSource MemoryStream leak with large images

I work with image files larger than 1 GB, creating Bitmapfrom a large one BitmapSourceand trying to get rid of the original BitmapSource. BitmapSourceremains in memory. This is usually an inconvenience, as it ultimately gets built, but with these large files, immediate memory cleanup is a necessity:

System.Drawing.Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
    BitmapEncoder enc = new BmpBitmapEncoder();
    enc.Frames.Add(BitmapFrame.Create(bitmapsource)); //large image
    enc.Save(outStream);
    bitmapsource = null;

    Bitmap temp = new System.Drawing.Bitmap(outStream);
    bitmap = temp.Clone(new Rectangle(0, 0, bm.Width, bm.Height), bm.PixelFormat);
    temp.Dispose();
}

GC.Collect();
GC.Collect();

//both bitmap and bitmapsource remain in memory

I came across here , but it BitmapSourcestill persists until much later in the pipeline.

+3
source share

All Articles