将System.Windows.Media.ImageSource转换为ByteArray [英] Convert System.Windows.Media.ImageSource to ByteArray

查看:43
本文介绍了将System.Windows.Media.ImageSource转换为ByteArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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转换为BitmapImage,但是得到了一个空对象.

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

推荐答案

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

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实际上是BitmapSource(而不是DrawingImage或D3DImage),则以下方法通过使用指定的BitmapEncoder(例如PngBitmapEncoder)将其转换为字节数组:

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):

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

这篇关于将System.Windows.Media.ImageSource转换为ByteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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