如何将WriteableBitmap对象转换为WPF中的BitmapImage对象

时间:2013-01-04 17:14:20

标签: wpf bitmapimage writeablebitmap

如何在WPF中将WriteableBitmap对象转换为BitmapImage对象?

This link涵盖了Silverlight,WPF中的过程不同,因为WriteableBitmap对象没有SaveJpeg方法。

所以我的问题是如何在WPF中将WriteableBitmap对象转换为BitmapImage对象?

1 个答案:

答案 0 :(得分:13)

您可以使用其中一个BitmapEncodersWriteableBitmap框架保存到新的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();