将MemoryStream设置为BitMapImage的源时出错
本文关键字:出错 BitMapImage MemoryStream 设置 | 更新日期: 2023-09-27 17:59:54
对于Windows Phone 8的开发,我读到的所有内容都说,为了将byte[]数组转换为位图图像,必须将流设置为位图图像的源。然而,当我实现这一点时,我在以下位置收到一个错误:
bitmapImage.SetSource(stream);
错误:
An exception of type 'System.Exception' occurred in System.Windows.ni.dll
but was not handled in user code
Additional information: The component cannot be found. (Exception from
HRESULT: 0x88982F50)
代码段:
byte[] bytes = value as byte[];
MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
存储在bytes
中的数组不是有效的映像。您需要进一步回到value
被填充的位置,并找出为什么它没有被图像的字节数组填充。
像这样的奇怪错误通常是由于未能将流设置到起始位置而导致的。此外,将一次性对象包装在using语句中也是一种很好的做法。
这能解决问题吗?
var bytes = value as byte[];
using(var stream = new MemoryStream(bytes, 0, bytes.Length))
{
//set this to the beginning of the stream
stream.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
}