关于c#:将字节数组转换为bitmapimage

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属性)绑定到stringUribyte[]类型的源属性时,将隐式调用ImageSourceConverter。


在第一种情况下,您在using块中定义了MemoryStream,当您离开该块时,这将导致对象被处置。因此,您返回带有处置(和不存在)流的BitmapImage

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