I am working of this answer, trying to convert an ImageSource to a BitmapImage. I have an Image control on a WPF canvas, the source of which is a bitmap, and I want to extract the source property of this control into a variable (which will be an ImageSource), and then cast this as a BitmapImage.
My code is below:
ImageSource source = MyImage.Source;
BitmapImage image = (BitmapImage) source;
It is basically the same code as in the linked answer, but I am getting the following runtime error on the second line (where I am trying to cast):
Unable to cast object of type 'System.Windows.Media.Imaging.BitmapFrameDecode' to type 'System.Windows.Media.Imaging.BitmapImage'.
The logical answer I guess is that this simply can't be done, but the answer linked is accepted, has a favorable comment and four upvotes which is frustrating. I am using Visual Studio 2012 with .Net 4.5, I have tried to compile against 4.0, 3.5 and 3.0, and am seeing the same issue.
I have also tried Ashura's suggestion here and the result is simply null (as in whenever I use the as keyword instead of casting the value of the resulting variable is null).
In my XAML, the source property of my Image control is a *.bmp file, I am ultimately trying to get this to a WriteableBitmap, but I need to have a BitmapImage to pass into the WriteableBitmap's constructor.
So my question is, what am I doing wrong? How do I convert from an ImageSource to a BitmapImage?