嘿,我正在尝试从字节数组加载 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/