将字节数组转换为bitmapimage

Hos*_*Rad 30 c# wpf bytearray bitmapimage

我要将字节数组转换为System.Windows.Media.Imaging.BitmapImageBitmapImage在图像控件中显示.

当我使用第一个代码时,注意到了!没有错误,也没有显示图像.但是当我使用第二个时,它工作正常!任何人都可以说发生了什么事吗?

第一个代码在这里:

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,Uribyte[].

  • 您提到了关于 `CacheOption` 的一个很好的观点,但是在您的代码中,`MemroyStream` 仍然会在加载图像之前被处理。除非调用 EndInit() 加载图像。是这样吗? (2认同)
  • 是的,这正是`BitmapCacheOption.OnLoad` 所做的。图像在“EndInit”期间同步加载。因此,在加载图像之前将*不*处理流。 (2认同)