c# - BitmapImage:访问关闭的 StreamSource

标签 c# wpf arrays bitmapimage

我正在使用以下代码尝试将我的 BitmapImage 转换为 byte[],这样我就可以将它保存在我的 MS SQL 数据库中。

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

遗憾的是这不起作用,因为当我尝试在 if 语句中访问它时 img.StreamSource 被释放,导致异常“无法访问已释放的文件”。

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

我怎样才能避免这种情况?

最佳答案

我终于设法让它工作了:

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

关于c# - BitmapImage:访问关闭的 StreamSource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9845019/

相关文章:

c# - "StandardOut has not been redirected or the process hasn' t started yet”在 C# 中读取控制台命令输出时

c# - C#/WPF访问MySQL的方式

javascript - Cordova/Phonegap - 当我关闭应用程序时存储一个数组(当我重新打开时使用它们)

c# - 无法对 DataGrid 中的日期列进行排序

c# - 如何禁用 Listview 标题上的上下文菜单

javascript - 将数组的内容插入另一个数组而不循环

java - Java中如何调用方法

原生 C++ 类的 C# 包装器

c# - Resharper冗余 'else'真的冗余吗?

C# - ASP.NET 按钮单击事件不起作用