C# 将字节数组转换为位图图像
我要将字节数组转换为C# 将字节数组转换为位图图像,c#,wpf,bytearray,bitmapimage,C#,Wpf,Bytearray,Bitmapimage,我要将字节数组转换为System.Windows.Media.Imaging.BitmapImage,并在图像控件中显示BitmapImage 当我使用第一个代码时,不会发生任何事情!没有错误,也没有显示图像。但是当我使用第二个时,它工作得很好!有人能说出发生了什么事吗 第一个代码如下: public BitmapImage ToImage(byte[] array) { using (System.IO.MemoryStream ms = new System.IO.MemoryStre
System.Windows.Media.Imaging.BitmapImage
,并在图像控件中显示BitmapImage
当我使用第一个代码时,不会发生任何事情!没有错误,也没有显示图像。但是当我使用第二个时,它工作得很好!有人能说出发生了什么事吗
第一个代码如下:
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;
}
}
public BitmapImage ToImage(byte[] array)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(array);
image.EndInit();
return image;
}
第二个代码如下:
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;
}
}
public BitmapImage ToImage(byte[] array)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(array);
image.EndInit();
return image;
}
在第一种情况下,您使用块在
中定义了MemoryStream
,这会导致在退出块时释放对象。因此,返回一个带有disposes(且不存在)流的BitmapImage
MemoryStream
s不保留非托管资源,因此您可以离开内存,让GC处理释放过程(但这不是一个好的做法)。在第一个代码示例中,在实际加载映像之前关闭流(通过使用块离开)。您还必须设置为立即加载图像,否则流需要保持打开,如第二个示例所示
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;
}
}
从中的备注部分:
如果需要,请将CacheOption属性设置为BitmapCacheOption.OnLoad
创建BitmapImage后关闭流
除此之外,您还可以使用内置类型转换从类型byte[]
转换为类型ImageSource
(或派生的BitmapSource
):
当您将ImageSource
类型的属性(例如图像控件的Source
属性)绑定到string
、Uri
或byte[]
类型的源属性时,会隐式调用ImageSourceConverter。您提到了CacheOption
的一个非常好的观点,但是在您的代码中,在加载映像之前,MemroyStream
仍将被处理。除非调用EndInit()
加载图像。是这样吗?是的,BitmapCacheOption.OnLoad
就是这样做的。图像在EndInit
期间同步加载。因此,在加载图像之前不会处理流。非常好。我不知道关于CacheOption
的那一点。我更改了代码,代码正常工作。我希望这是JWTDO,但在Windows应用商店应用程序中,我发现,“错误1'Windows.UI.Xaml.Media.Imaging.BitmapImage'不包含'BeginInit'的定义,并且找不到接受'Windows.UI.Xaml.Media.Imaging.BitmapImage'类型的第一个参数的扩展方法'BeginInit'(您是否缺少一个using…”Windows Runtime和WPF是两个不同的框架。Windows Runtime中没有BeginInit和EndInit。只需调用即可。请查看关于不处理MemoryStream的内容。这至少被认为是一种不好的做法。@Clemens感谢您的评论和回答。