0

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

leppie
  • 115,091
  • 17
  • 196
  • 297
curiousity
  • 4,703
  • 8
  • 39
  • 59

2 Answers2

2

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.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • still error(( "No imaging component for this operation found" in bmpImage.EndInit(); line – curiousity Nov 28 '11 at 16:41
  • 1
    @curiousity: Of course it does not work if you use `CopyPixels`, that method does not copy any meta-information which is expected by `BitmapImage`. `BitmapImage` expects a fully encoded stream, with file format header. – H.B. Nov 28 '11 at 18:19
1

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.

Kevin B Burns
  • 1,032
  • 9
  • 24