如何在WPF中将WriteableBitmap
对象转换为BitmapImage
对象?
This link涵盖了Silverlight,WPF中的过程不同,因为WriteableBitmap
对象没有SaveJpeg
方法。
所以我的问题是如何在WPF中将WriteableBitmap
对象转换为BitmapImage
对象?
答案 0 :(得分:13)
您可以使用其中一个BitmapEncoders
将WriteableBitmap
框架保存到新的BitmapImage
在此示例中,我们将使用PngBitmapEncoder
,但只需选择适合您情况的那个。
public BitmapImage ConvertWriteableBitmapToBitmapImage(WriteableBitmap wbm)
{
BitmapImage bmImage = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);
bmImage.BeginInit();
bmImage.CacheOption = BitmapCacheOption.OnLoad;
bmImage.StreamSource = stream;
bmImage.EndInit();
bmImage.Freeze();
}
return bmImage;
}
用法:
BitmapImage bitmap = ConvertWriteableBitmapToBitmapImage(your writable bitmap);
或者你可以使这个扩展方法易于使用
public static class ImageHelpers
{
public static BitmapImage ToBitmapImage(this WriteableBitmap wbm)
{
BitmapImage bmImage = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(wbm));
encoder.Save(stream);
bmImage.BeginInit();
bmImage.CacheOption = BitmapCacheOption.OnLoad;
bmImage.StreamSource = stream;
bmImage.EndInit();
bmImage.Freeze();
}
return bmImage;
}
}
用法:
WriteableBitmap wbm = // your writeable bitmap
BitmapImage bitmap = wbm.ToBitmapImage();