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);
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/495455ToImagefunction looks odd - arrh its a void not a function and I'm still guessing whatencoderis, but see the last two functions here showing what a typical ByteArray to Image converter function looks like: stackoverflow.com/a/26729513/495455var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);. So you preserve the image.decoder.Frames[0]is your BitmapSource. -- You can set theStreamSourceof a BitmapImage to a new MemoryStream (i.e., don't overwrite the current Stream), if you actually need a BitmapImage.