简体   繁体   中英

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM