BitmapImage to Bitmap throw exception

389 Views Asked by At

i use for a project a function that i found on StackOverflow : https://stackoverflow.com/a/6484754/9535211
The goal of this function is to convert a System.Windows.Media.Imaging.BitmapImage to a System.Drawing.Bitmap.

public Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{

            using (MemoryStream outStream = new MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(bitmapImage));
                enc.Save(outStream);
                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
                return (new Bitmap(bitmap));
            }
}

It works pretty well (even if its realy heavy), but it throw an exception everytime its called : Exception thrown: 'System.NotSupportedException' in PresentationCore.dll
It seems that it comes from the line :

enc.Save(outStream);

Is there a way to make it disappear ?
Thanks for your help !

1

There are 1 best solutions below

6
On

You should check to ensure that the BitmapImage you're passing in is valid. According to the documentation for BitmapEncoder.Save, the error you're getting is a result of the "Frames" count being less than or equal to zero.

Ensure that the frame is being added properly and that your bitmapImage is being passed in with the correct values.