I’m writing a control to show images.
My problem comes out using Image class on multipage TIFFs.
I use this (I post only relevant code) at the beginning:
Image img;
int pages;
img = Bitmap.FromFile(filename);
pages = img.GetFrameCount(FrameDimension.Page);
then, when the user wants to show a different page:
public override Image GetPage(int page)
{
if (page < 1 || page > pages) return null;
try
{
#if !TEST
img.SelectActiveFrame(FrameDimension.Page, page - 1);
return new Bitmap(img);
#else
MemoryStream ms = new MemoryStream();
img.SelectActiveFrame(FrameDimension.Page, page - 1);
img.Save(ms, ImageFormat.Jpeg);
Image ret = Image.FromStream(ms);
ms.Flush();
ms.Dispose();
return ret;
#endif
}
catch (Exception ex)
{
"Tiff GetPage error: {0}".ToDebug(ex.Message);
return null;
}
}
Using img.SelectActiveFrame(FrameDimension.Page, page - 1); (in both versions) about 7MB are allocated in memory and those are never freed (even exiting the method)!!!
If I goes to next page 7MB are allocated and not freed everytime, while going back (on an already visited pages) previously allocated memory is used.
To give you an example: think Task Manager reports my app is using x MB; going one page forward memory increases to x + y (after SelectActiveFrame()) + z (Image ret = ...). Well, I should have x + z (y part should be zero or GC collected exiting the method), but obviously that’s not what happens, even calling GC.Collect manually.
Going back to a previously visited page, memory increases effectively only with z, as expected.
I find it terrible (think about a file with 80 pages…), but how can I force img object to free allocated memory? Am I doing something wrong?
I’ve already thought closing and reopening img, but speed is not good.
Thanks to everybody
If I’m not mistaken you’re not destroying the used controls at every possible point.
I think you might need to test this – but make sure that you’re disposing all the used controls.
ie.
ImageControlUsed.Dispose();