I have the following method, to convert a BitmapImage
to a System.Drawing.Bitmap
:
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
Bitmap bitmap;
using (var ms = new MemoryStream())
{
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(ms);
bitmap = new Bitmap(ms);
}
return bitmap;
}
Whenever I try and use the returned Bitmap object, I get the following error:
OutOfMemoryException occured - Out of memory.
However, whenever I replace the code with this:
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
var ms = new MemoryStream();
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(ms);
return new Bitmap(ms);
}
This works fine. However, I am pretty sure that I am supposed to use using as the MemoryStream
object implements IDisposable
. What's going on here?