how to convert byte[] into BitmapFrame c#

2.1k views Asked by At

I have tryed this but have exception - Operation is not valide due to current state of the object

private BitmapFrame backconvertor(byte[] incomingBuffer)
    {
        BitmapImage bmpImage = new BitmapImage();
        MemoryStream mystream = new MemoryStream(incomingBuffer);
        bmpImage.StreamSource = mystream;
        BitmapFrame bf = BitmapFrame.Create(bmpImage);
        return bf;
    }

Error rising when I am trying to

return backconvertor(buff); 

in other function (buff - is ready!)

2

There are 2 answers

2
Jim Mischel On

Documentation indicates that in order to initialize the image, you need to do it between BeginInit and EndInit. That is:

bmpImage.BeginInit();
bmpImage.StreamSource = mystream;
bmpImage.EndInit();

Or, you can pass the stream to the constructor:

bmpImage = new BitmapImage(mystream);

See http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.begininit.aspx for an example and more discussion of BeginInit.

0
Kevin B Burns On

This is what I have in a WPF Converter to handle byte to BitmapFrame and it works perfectly:

            var imgBytes = value as byte[];
            if (imgBytes == null)
                return null;
            using (var stream = new MemoryStream(imgBytes))
            {
                return BitmapFrame.Create(stream,
                    BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
            }

Also its thread safe as I have used it in Task.Run before also.