如何在WPF中将WriteableBitmap对象转换为BitmapImage对象 [英] How do I convert a WriteableBitmap object to a BitmapImage Object in WPF

查看:166
本文介绍了如何在WPF中将WriteableBitmap对象转换为BitmapImage对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆