I have to make some thumbnail from specific parts of a large image and save them as png/jpeg images. Here is what I'm doing:
public static void Save(BitmapImage srcBitmap, Int32Rect srcRegion, Rect destRegion)
{
var cropped = new CroppedBitmap(srcBitmap, srcRegion);
var drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawImage(cropped, destRegion);
}
var bmp = new RenderTargetBitmap(256, 256, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
var bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(bmp));
using (var filestream = new FileStream(path, FileMode.Create))
{
bitmapEncoder.Save(filestream);
}
}
I may call this method using a single large Bitmap with different srcRegion for thousand times, the application increasingly consume more RAM and finally throws System.OutOfMemoryException! Seems there is a memory leak in this function but I don't know where it is. Anyone can help?
EDIT: also I'm not sure whether this is the best way of getting a portion of a large image and resizing that portion into a smaller image (e.g. 256*256) and saving it. Is there any better idea?

destRegionever different from(0, 0, 256, 256), and does the size ofsrcRegionever differ from(256, 256)? If not, you may probably directly pass the CroppedBitmap to the BitmapEncoder, without using a DrawingVisual and a RenderTargetBtmap.System.Drawing.Bitmapit cannot be created for very large images (e.g: 300MB) but I can useBitmapImageto handle such large images.