wpf 将 System.Windows.Media.ImageSource 转换为 ByteArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29380416/
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 13:03:29  来源:igfitidea点击:

Convert System.Windows.Media.ImageSource to ByteArray

c#wpf

提问by Benjamin Martin

is there a way to convert a ImageSource object to byte array? I have an ImageSource object bound to a WPF window, i can convert a byte array from the data base and convert it to ImageSource but i can't do it the reverse way.

有没有办法将 ImageSource 对象转换为字节数组?我有一个绑定到 WPF 窗口的 ImageSource 对象,我可以从数据库转换一个字节数组并将其转换为 ImageSource 但我不能以相反的方式进行。

Thx in advance.

提前谢谢。

Edit: I tried to convert ImageSource as BitmapImage but got a null object.

编辑:我试图将 ImageSource 转换为 BitmapImage 但得到了一个空对象。

回答by Clemens

Even if your ImageSource is not a BitmapImage you may still successfully cast it to BitmapSource, which is the base class of all WPF bitmap classes like BitmapImage, BitmapFrame, WriteableBitmap, RenderTargetBitmap etc. (see here).

即使您的 ImageSource 不是 BitmapImage,您仍然可以成功地将其转换为BitmapSource,这是所有 WPF 位图类(如 BitmapImage、BitmapFrame、WriteableBitmap、RenderTargetBitmap 等)的基类(请参见此处)。

So in case your ImageSource is actually a BitmapSource (and not a DrawingImage or a D3DImage), the following method converts it to a byte array by using the specified BitmapEncoder (e.g. a PngBitmapEncoder):

因此,如果您的 ImageSource 实际上是 BitmapSource(而不是 DrawingImage 或 D3DImage),以下方法将使用指定的 BitmapEncoder(例如 PngBitmapEncoder)将其转换为字节数组:

public byte[] ImageSourceToBytes(BitmapEncoder encoder, ImageSource imageSource)
{
    byte[] bytes = null;
    var bitmapSource = imageSource as BitmapSource;

    if (bitmapSource != null)
    {
        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

        using (var stream = new MemoryStream())
        {
            encoder.Save(stream);
            bytes = stream.ToArray();
        }
    }

    return bytes;
}