小编典典

将字节数组转换为bitmapimage

c#

我要将字节数组转换为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;
   }
}

第二个代码在这里:

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

阅读 264

收藏
2020-05-19

共1个答案

小编典典

在第一个代码示例中,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的“备注”部分:

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


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

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

当您类型的属性绑定ImageSourceConverter被隐式调用ImageSource(如Image控件的Source属性),以类型的源属性stringUribyte[]

2020-05-19