将字节数组转换为bitmapimage

时间:2013-01-15 11:50:01

标签: 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;
   }
}

第二个代码在这里:

public BitmapImage ToImage(byte[] array)
{
   BitmapImage image = new BitmapImage();
   image.BeginInit();
   image.StreamSource = new System.IO.MemoryStream(array);
   image.EndInit();
   return image;
 }

2 个答案:

答案 0 :(得分:53)

在第一个代码示例中,在实际加载图像之前关闭流(通过离开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;
    }
}

来自BitmapImage.StreamSource的备注部分:

  

如果您愿意,请将CacheOption属性设置为BitmapCacheOption.OnLoad   在创建BitmapImage之后关闭流。


除此之外,您还可以使用内置类型转换从类型byte[]转换为类型ImageSource(或派生的BitmapSource):

var bitmap = (BitmapSource)new ImageSourceConverter().ConvertFrom(array);

当您将类型为ImageSource的属性(例如,图像控件的Source属性)绑定到类型为stringUri或{的源属性时,将隐式调用ImageSourceConverter {1}}。

答案 1 :(得分:4)

在第一种情况下,您在MemoryStream块中定义了using,这会导致在您离开块时处置对象。因此,您返回BitmapImage,其中包含disposes(和不存在的)流。

MemoryStream不保留任何非托管资源,因此您可以保留内存并让GC处理释放过程(但这不是一个好习惯)。