将字节数组转换为位图图像 [英] convert array of bytes to bitmapimage

查看:37
本文介绍了将字节数组转换为位图图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm going to convert array of bytes to System.Windows.Media.Imaging.BitmapImage and show the BitmapImage in an image control.

当我使用第一个代码时,注意发生了!没有错误,也没有显示图像.但是当我使用第二个时它工作正常!谁能说说这是怎么回事?

When I'm using the first code, noting happens! no error and no image is displayed. But when I'm using the second one it works fine! can anyone say what is going on?

第一个代码在这里:

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;
 }

推荐答案

在第一个代码示例中,在实际加载图像之前关闭流(通过离开 using 块).您还必须设置 BitmapCacheOptions.OnLoad以实现立即加载图像,否则流需要保持打开状态,如您的第二个示例.

In the first code example the stream is closed (by leaving the using block) before the image is actually loaded. You must also set BitmapCacheOptions.OnLoad to achieve that the image is loaded immediately, otherwise the stream needs to be kept open, as in your second example.

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 后关闭流.

Set the CacheOption property to BitmapCacheOption.OnLoad if you wish to close the stream after the BitmapImage is created.

<小时>

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


Besides that, you can also use built-in type conversion to convert from type byte[] to type ImageSource (or the derived BitmapSource):

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

当您将 ImageSource 类型的属性(例如 Image 控件的 Source 属性)绑定到 stringImageSourceConverter>、Uribyte[].

ImageSourceConverter is called implicitly when you bind a property of type ImageSource (e.g. the Image control's Source property) to a source property of type string, Uri or byte[].

这篇关于将字节数组转换为位图图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆