Hos*_*Rad 30 c# wpf bytearray bitmapimage
我要将字节数组转换为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;
}
}
Run Code Online (Sandbox Code Playgroud)
第二个代码在这里:
public BitmapImage ToImage(byte[] array)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(array);
image.EndInit();
return image;
}
Run Code Online (Sandbox Code Playgroud)
Cle*_*ens 57
在第一个代码示例中,using在实际加载图像之前关闭流(通过离开块).您还必须设置BitmapCacheOptions.OnLoad以实现图像立即加载,否则流需要保持打开,如第二个示例中所示.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
从BitmapImage.StreamSource中的Remarks部分:
如果要在创建BitmapImage后关闭流,请将CacheOption属性设置为BitmapCacheOption.OnLoad.
除此之外,您还可以使用内置类型转换将类型转换byte[]为类型ImageSource(或派生类型BitmapSource):
var bitmap = (BitmapSource)new ImageSourceConverter().ConvertFrom(array);
Run Code Online (Sandbox Code Playgroud)
当您类型的属性绑定ImageSourceConverter被隐式调用ImageSource(如Image控件的Source属性),以类型的源属性string,Uri或byte[].
| 归档时间: |
|
| 查看次数: |
39575 次 |
| 最近记录: |