c# - 从字节数组加载 WPF 图像控件

标签 c# .net wpf

嘿,我正在尝试从字节数组加载 Image 控件,我已经尝试了在网上找到的多种解决方案(尤其是本网站),但似乎没有任何效果。 我的主要目标是从字节数组中获取 ImageSource 并从转换器返回它。

我试过:

BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(lBytes);
bi.EndInit();

但这失败了:

NotSupportedException

No imaging component suitable to complete this operation was found.

还尝试先加载一个 Bitmap,然后尝试从那里获取 ImageSource

using (MemoryStream lMem = new MemoryStream(lBytes))
{
        TypeConverter tc = TypeDescriptor.GetConverter(typeof(System.Drawing.Bitmap));
        System.Drawing.Bitmap b = (System.Drawing.Bitmap)tc.ConvertFrom(lBytes);
        lResult = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            b.GetHbitmap(),
            IntPtr.Zero,
            System.Windows.Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());

        b.Dispose();
}

但这在 ConvertFrom 上失败并显示“参数无效。”

在我的文件系统中加载有效的 PNG 文件时的所有这些。

我的想法用完了,有什么线索吗?

谢谢。

编辑:

好的,问题是我加载文件的方式...

我在用

using (FileStream lFileStream = new FileStream(pFilePath, FileMode.Open))
{
    using (StreamReader lReader = new StreamReader(lFileStream))
    {
        BinaryFormatter bf = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            string lString = lReader.ReadToEnd();
            bf.Serialize(ms, lString);
            ms.Seek(0, 0);
            lImage = ms.ToArray();
        } 
        lResult = new Graphic(lImage);
    }
}

但后来读到我可以使用:

lImage = File.ReadAllBytes(pFilePath);

就是这样。

谢谢。

最佳答案

第一个解决方案工作正常,但我认为你的问题是关于如何读取数组字节而不是如何将数组转换为位图。
我已经多次使用该解决方案。我的解决方案和您的解决方案之间的区别在于如何读取文件并将其转换为数组。

我只是使用:

System.IO.File.ReadAllBytes(filepath)

关于c# - 从字节数组加载 WPF 图像控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5997683/

相关文章:

c# - 配置连接、命令、适配器

c# - 将 WPF DataGrid 绑定(bind)到 List<Interface>

c# - 从通用列表中查找项目

c# - 如何以编程方式更改 rdlc 报告中的数据表

C# 持续监视正在重新创建的文件

.net - 如何列出 GAC 中所有已注册的程序集?

c# - XamlParseException 是未处理的 C# 应用程序

c# - 检查数字数组是否连续的功能方法

c# - 计算圆内坐标

wpf - 如何将我的 MVVM 集合连接到我的业务层中长时间运行的进程?