[英]Why am I getting a runtime error when I try to convert from an ImageSource to a BitmapImage?
I am working of this answer , trying to convert an ImageSource to a BitmapImage.我正在处理这个答案,试图将 ImageSource 转换为 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.
我在 WPF 画布上有一个 Image 控件,它的源是一个位图,我想将该控件的源属性提取到一个变量中(将是一个 ImageSource),然后将其转换为一个 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'.
无法将“System.Windows.Media.Imaging.BitmapFrameDecode”类型的对象转换为“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.
我正在使用带有 .Net 4.5 的 Visual Studio 2012,我尝试针对 4.0、3.5 和 3.0 进行编译,但我看到了同样的问题。
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).我也在这里尝试过Ashura的建议,结果只是空的(就像我使用as关键字而不是将结果变量的值转换为空时一样)。
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.在我的 XAML 中,我的 Image 控件的源属性是一个*.bmp文件,我最终试图将其转换为 WriteableBitmap,但我需要有一个 BitmapImage 来传递到 WriteableBitmap 的构造函数中。
So my question is, what am I doing wrong?所以我的问题是,我做错了什么? How do I convert from an ImageSource to a BitmapImage?
如何从 ImageSource 转换为 BitmapImage?
Thank you to the commenters, you helped me understand the problem.感谢评论者,你帮助我理解了问题。
I ended up taking the Source property out of my XAML, and set the below in the Window Loaded event to ensure that the Source property of my image control was indeed a BitmapImage:我最终从 XAML 中取出Source属性,并在Window Loaded事件中设置以下内容,以确保我的图像控件的Source属性确实是 BitmapImage:
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
var image = new BitmapImage(new Uri("sample.bmp", UriKind.Relative));
MyImage.Source = image;
}
If you do this in the XAML instead, the Source property ends up being a BitmapFrameDecode object by default.如果改为在 XAML 中执行此操作,则默认情况下 Source 属性最终会成为BitmapFrameDecode对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.