byte[] to BitmapImage conversion fails

为君一笑 提交于 2019-12-02 05:00:16

问题


I have a problem. I want to convert BitmapImage into byte[] array and back.

I wrote these methods:

public static byte[] ToByteArray(this BitmapImage bitmapImage)
{
    byte[] bytes;
    using (MemoryStream ms = new MemoryStream())
    {
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource.CopyTo(ms);
        bitmapImage.EndInit();
        bytes = ms.ToArray();
    }
    return bytes;
}

public static BitmapImage ToBitmapImage(this byte[] bytes, int width, int height)
{
    BitmapImage bitmapImage = new BitmapImage();
    using (MemoryStream ms = new MemoryStream(bytes))
    {
        ms.Position = 0;
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = ms;
        bitmapImage.EndInit(); // HERE'S AN EXCEPTION!!!
    }
    return bitmapImage;
}

First one works fine, but when I try to convert from byte[] into BitmapImage I got a NotSupportedException... Why? How to correct the code of the 2nd method?


回答1:


There are two problems with your ToByteArray method.

First it calls BeginInit and EndInit on an already initialized BitmapImage instance. This is not allowed, see the Exceptions list in BeginInit.

Second, the method could not be called on a BitmapImage that was created from an Uri instead of a Stream. Then the StreamSource property would be null.

I suggest to implement the method like shown below. This implementation would work for any BitmapSource, not only BitmapImages. And you are able to control the image format by selecting an appropriate BitmapEncoder, e.g. JpegBitmapEncoder instead of PngBitmapEncoder.

public static byte[] ToByteArray(this BitmapSource bitmap)
{
    var encoder = new PngBitmapEncoder(); // or any other encoder
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    using (var ms = new MemoryStream())
    {
        encoder.Save(ms);
        return ms.ToArray();
    }
}

An image buffer returned by this ToByteArray method can always be converted back to a BitmapImage by your ToBitmapImage method.

And please note that the width and height arguments of your ToBitmapImage method are currently unused.


UPDATE

An alternative implementation of the decoding method could look like shown below, although it does not return a BitmapImage but only an instance of the base class BitmapSource. You may however change the return type to BitmapFrame.

public static BitmapSource ToBitmapImage(this byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        return decoder.Frames[0];
    }
}


来源:https://stackoverflow.com/questions/14299802/byte-to-bitmapimage-conversion-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!