BitmapImage: Accessing closed StreamSource

2019-03-02 10:49发布

问题:

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