curiousity
curiousity

Reputation: 4741

how to convert byte[] into BitmapFrame c#

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

Upvotes: 0

Views: 2143

Answers (2)

Kevin B Burns
Kevin B Burns

Reputation: 1067

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.

Upvotes: 1

Jim Mischel
Jim Mischel

Reputation: 133950

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.

Upvotes: 2

Related Questions