convert array of bytes to bitmapimage

前端 未结 2 1691
时光说笑
时光说笑 2020-11-27 06:31

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 u

相关标签:
2条回答
  • 2020-11-27 07:04

    In the first case, you defined your MemoryStream in a using block, which causes the object to be disposed when you go out of the block. So you return a BitmapImage with a disposes (and non-existing) stream.

    MemoryStreams keep no unmanaged resources, so you can leave the memory and let the GC handle the freeing process (but that's not a good practice).

    0 讨论(0)
  • 2020-11-27 07:06

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

    From the Remarks section in BitmapImage.StreamSource:

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


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

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

    0 讨论(0)
提交回复
热议问题