将 MemoryStream 设置为 BitMapImage 的源时出错

Error when setting MemoryStream as the source of a BitMapImage

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

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

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