BitmapImage:访问封闭的StreamSource [英] BitmapImage: Accessing closed StreamSource

查看:89
本文介绍了BitmapImage:访问封闭的StreamSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码尝试将BitmapImage转换为字节[],以便将其保存在MS SQL数据库中.

I'm using the following code trying to convert my BitmapImage to a byte[] so I can save it in my MS SQL Database.

    public static byte[] BufferFromImage(BitmapImage img)
    {
        if (img == null)
            return null;

            byte[] result = null;
            using (Stream stream = img.StreamSource)
            {
                if (stream != null && stream.Length > 0)
                {
                    using (BinaryReader br = new BinaryReader(stream))
                    {
                        result = br.ReadBytes((int)(stream.Length));
                    }
                }
            }

            return result;
        }

可悲的是,这无法作为img使用.当我尝试在if语句中访问它时,StreamSource被处置,从而导致异常无法访问已处置的文件".

Sadly this doesn't work as img.StreamSource is disposed when I try to access it in the if-statement, resulting in an exception "Cannot access a disposed file".

我的电话: BufferFromImage(imgLogo.Source as BitmapImage);

如何避免这种情况?

推荐答案

我终于设法使其正常工作:

I finally managed to get it working:

    public static byte[] BufferFromImage(BitmapImage img)
    {
        byte[] result = null;

        if (img != null)
        {
            using(MemoryStream memStream = new MemoryStream())
            {
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(img));
                encoder.Save(memStream);

                result = memStream.ToArray();
            }

        }

        return result;
    }

这篇关于BitmapImage:访问封闭的StreamSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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