将MemoryStream设置为BitMapImage的源时出错

时间:2015-06-26 20:14:30

标签: c# windows-phone-8 memorystream bitmapimage

对于Windows Phone 8开发,我读过的所有内容都表示你必须将一个流设置为bitmapimage的源,以便将byte []数组转换为bitmapimage。当我实现这个时,我收到错误:

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

2 个答案:

答案 0 :(得分:1)

这种奇怪的错误通常是由于未能将流设置为起始位置引起的。此外,最好将一次性对象包装在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);
 }

答案 1 :(得分:1)

您在bytes中存储的数组不是有效图像。您需要进一步回到value填充的位置,并找出为什么没有填充图像的字节数组。