convert array of bytes to bitmapimage
我将把字节数组转换为System.Windows.Media.Imaging.BitmapImage,并在图像控件中显示BitmapImage。
当我使用第一个代码时,会发生注意! 没有错误,没有图像显示。 但是,当我使用第二个时,它工作正常! 谁能说这是怎么回事?
第一个代码在这里:
1 2 3 4 5 6 7 8 9 10 11
| public BitmapImage ToImage (byte[] array )
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(array ))
{
BitmapImage image = new BitmapImage ();
image .BeginInit();
image .StreamSource = ms ;
image .EndInit();
return image ;
}
} |
第二个代码在这里:
1 2 3 4 5 6 7 8
| public BitmapImage ToImage (byte[] array )
{
BitmapImage image = new BitmapImage ();
image .BeginInit();
image .StreamSource = new System.IO.MemoryStream(array );
image .EndInit();
return image ;
} |
在第一个代码示例中,在实际加载图像之前关闭流(通过保留using块)。您还必须设置BitmapCacheOptions.OnLoad来立即加载图像,否则,如第二个示例所示,流必须保持打开状态。
1 2 3 4 5 6 7 8 9 10 11 12
| public BitmapImage ToImage (byte[] array )
{
using (var ms = new System.IO.MemoryStream(array ))
{
var image = new BitmapImage ();
image .BeginInit();
image .CacheOption = BitmapCacheOption .OnLoad; // here
image .StreamSource = ms ;
image .EndInit();
return image ;
}
} |
从BitmapImage.StreamSource的"备注"部分中:
Set the CacheOption property to BitmapCacheOption.OnLoad if you wish
to close the stream after the BitmapImage is created.
除此之外,还可以使用内置类型转换将类型从byte[]转换为类型ImageSource(或派生的BitmapSource):
1
| var bitmap = (BitmapSource )new ImageSourceConverter ().ConvertFrom(array ); |
当您将ImageSource类型的属性(例如Image控件的Source属性)绑定到string,Uri或byte[]类型的源属性时,将隐式调用ImageSourceConverter。
-
您提到了关于CacheOption的一个很好的观点,但是在您的代码中,MemroyStream仍将在加载图像之前被销毁。除非调用EndInit()加载图像。是这样吗
-
是的,这正是BitmapCacheOption.OnLoad的作用。在EndInit期间同步加载图像。因此,在加载图像之前不会处理流。
-
非常好。我不知道关于CacheOption的观点。我更改了代码,它可以正常工作。
-
我希望这是JWTDO,但是在Windows Store应用程序中,我得到"错误1 Windows.UI.Xaml.Media.Imaging.BitmapImage不包含BeginInit的定义,并且没有扩展方法BeginInit接受Windows类型的第一个参数可以找到.UI.Xaml.Media.Imaging.BitmapImage(您是否缺少使用..."
-
Windows Runtime和WPF是两个不同的框架。 Windows运行时中没有BeginInit和EndInit。只需调用SetSourceAsync即可。
在第一种情况下,您在using块中定义了MemoryStream,当您离开该块时,这将导致对象被处置。因此,您返回带有处置(和不存在)流的BitmapImage。
MemoryStream不会保留任何非托管资源,因此您可以保留内存并让GC处理释放过程(但这不是一个好习惯)。
-
请参阅有关不处置MemoryStream的答案。它至少被认为是不好的做法。
-
@Clemens感谢您的评论和好的回答。