I have a WPF application where I am saving couple of hundreds of BitmapSources by converting them to TIFF images using TiffBitmapEncoder. However, I have this strange memory consumption which is often throwing Insufficient Memory Exception.
NOTE:
- I have 8GB of ram installed.
- The image sizes vary from 10x10 to 300x300 pixels (quite small)
Here is the code which works:
static void SaveBitmapSource(BitmapSource bitmapSource)
{
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Zip;
BitmapFrame frame = BitmapFrame.Create(bitmapSource);
encoder.Frames.Add(frame);
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
}
}
And here is the screen shot of my memory:
Now if I clone the BitmapSource (even just once) then I get this huge memory allocation causing the Insufficient Memory Exception.
static BitmapSource source2 = null;
static void SaveBitmapSource(BitmapSource bitmapSource)
{
if (source2 == null)
{
source2 = bitmapSource.Clone();
}
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Zip;
BitmapFrame frame = BitmapFrame.Create(source2);
encoder.Frames.Add(frame);
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
}
}
Here is the screenshot of my memory for the second code sample
Does anyone know what could be causing this and how to fix it?
The difference is that the BitmapSource in the first example has been rendered to the screen and the second one hasn't. My suspicions are this could be something to do with GPU and the Dispatcher that might be hardware accelerating the conversion whereas the second one is done on CPU where there is some sort of a bug...
Tried:
- Tried calling
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
after theSaveBitmapSource()
with no luck