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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14161665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:53:49  来源:igfitidea点击:

How do I convert a WriteableBitmap object to a BitmapImage Object in WPF

wpfbitmapimagewriteablebitmap

提问by JMK

How do I convert a WriteableBitmapobject to a BitmapImageObject in WPF?

如何将WriteableBitmap对象转换为BitmapImageWPF 中的对象?

This linkcovers silverlight, the process is not the same in WPF as the WriteableBitmapobject does not have a SaveJpegmethod.

此链接涵盖了 Silverlight,该过程与 WPF 中的过程不同,因为WriteableBitmap对象没有SaveJpeg方法。

So my question is How do I convert a WriteableBitmapobject to a BitmapImageObject in WPF?

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

回答by sa_ddam213

You can use one of the BitmapEncodersto save the WriteableBitmapframe to a new BitmapImage

您可以使用其中之一BitmapEncodersWriteableBitmap帧保存到新的BitmapImage

In this example we will use the PngBitmapEncoderbut just choose the one that fits your situation.

在本例中,我们将使用 ,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;
}

usage:

用法:

 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;
    }
}

usage:

用法:

WriteableBitmap wbm = // your writeable bitmap

BitmapImage bitmap = wbm.ToBitmapImage();