using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
public static class WriteableBitmapExtensions
{
///
/// Convert the WriteableBitmap to GDI+ Bitmap.
///
/// The writeable bitmap.
/// returns a System.Drawing.Bitmap Bitmap.
public static System.Drawing.Bitmap ConvertToGDIBitmap(this WriteableBitmap bitmapsource)
{
using (MemoryStream stream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(stream);
using (var tempBitmap = new System.Drawing.Bitmap(stream))
{
// According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
// So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
var result = new System.Drawing.Bitmap(tempBitmap);
stream.Dispose();
return result;
}
}
}
///
/// Convert the WriteableBitmap to BitmapImage.
///
/// The writeable bitmap.
/// returns a new instance of BitmapImage
public static BitmapImage ConvertToBitmapImage(this WriteableBitmap bitmapSource)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();
encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
bImg.EndInit();
memoryStream.Close();
return bImg;
}
}