如何在WPF中将WriteableBitmap对象转换为BitmapImage对象 [英] How do I convert a WriteableBitmap object to a BitmapImage Object in WPF
问题描述
如何在WPF中将WriteableBitmap
对象转换为BitmapImage
对象?
How do I convert a WriteableBitmap
object to a BitmapImage
Object in WPF?
此链接涵盖了Silverlight,过程不尽相同在WPF中,因为WriteableBitmap
对象没有SaveJpeg
方法.
This link covers silverlight, the process is not the same in WPF as the WriteableBitmap
object does not have a SaveJpeg
method.
所以我的问题是如何在WPF中将WriteableBitmap
对象转换为BitmapImage
对象?
So my question is How do I convert a WriteableBitmap
object to a BitmapImage
Object in WPF?
推荐答案
您可以使用BitmapEncoders
之一将WriteableBitmap
框架保存到新的BitmapImage
You can use one of the BitmapEncoders
to save the WriteableBitmap
frame to a new BitmapImage
在此示例中,我们将使用PngBitmapEncoder
,但只需选择适合您情况的那个.
In this example we will use the PngBitmapEncoder
but just choose the one that fits your situation.
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);
或者您可以将其作为易于使用的扩展方法
or you could make this an extension method for easy use
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();
这篇关于如何在WPF中将WriteableBitmap对象转换为BitmapImage对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!