title: OutOfMemoryException while working with Images in WPF
body: <p>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:</p>
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>I may call this method using a single large <code>Bitmap</code> with different <code>srcRegion</code> for thousand times, the application increasingly consume more RAM and finally throws <code>System.OutOfMemoryException</code>! Seems there is a memory leak in this function but I don't know where it is. Anyone can help?</p>
  
  <p><strong>EDIT:</strong> 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?</p>
  
  <p><a href="https://i.stack.imgur.com/862pv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/862pv.jpg" alt="enter image description here"></a></p>