0

I keep getting this error: Operation is not valid due to the current state of the object here is my code

      public BitmapImage ToImage(byte[] array)
    {
      
        using (var stream = new MemoryStream(array))
        {
            var encoder = new PngBitmapEncoder();
            BitmapImage image = new BitmapImage();

            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad; // here
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);

           // image.StreamSource = stream;
            image.EndInit();
            return image;
        }
    }

any ideas?

Update: public BitmapImage ToImage(byte[] array) {

        using (var stream = new MemoryStream(array))
        {
            var encoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
            BitmapImage image = new BitmapImage();

            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad; // here
           
           // image.StreamSource = stream;
            image.EndInit();
            return image;
        }
    }

I got this error : No imaging component suitable to complete this operation was found.' Inner Exception COMException: The component cannot be found. (Exception from HRESULT: 0x88982F50)

on

 var encoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
6
  • What is encoder? Looks like you want to make a vid or gif with frames? If its the latter I've written the "Make an Animate Gif" code here stackoverflow.com/a/13486374/495455 Commented Feb 21, 2022 at 5:21
  • Also your ToImage function looks odd - arrh its a void not a function and I'm still guessing what encoder is, but see the last two functions here showing what a typical ByteArray to Image converter function looks like: stackoverflow.com/a/26729513/495455 Commented Feb 21, 2022 at 5:24
  • Jeremy Thompson, I was using var encoder = new PngBitmapEncoder(); to set my pixel format Commented Feb 21, 2022 at 5:50
  • var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);. So you preserve the image. decoder.Frames[0] is your BitmapSource. -- You can set the StreamSource of a BitmapImage to a new MemoryStream (i.e., don't overwrite the current Stream), if you actually need a BitmapImage. Commented Feb 21, 2022 at 8:10
  • Jimi, please see my update. Is that what you meant ? I got a runtime error Commented Feb 21, 2022 at 15:17

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.