BitmapImage: Accessing closed StreamSource

筅森魡賤 提交于 2019-12-02 06:54:04

问题


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

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".

My call: BufferFromImage(imgLogo.Source as BitmapImage);

How can I avoid this?


回答1:


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


来源:https://stackoverflow.com/questions/9845019/bitmapimage-accessing-closed-streamsource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!