为什么我会得到一个运行时错误,当我尝试从一个ImageSource的转换为BitmapImage的?我会、当我、转换为、错误

2023-09-08 08:34:47 作者:躺在你的梨涡里

我的工作这个答案,试图以一个ImageSource的转换为BitmapImage的。我有一个WPF画布图像控制,源这是一个位图,我想这个源头控制属性提取到一个变量(这将是一个ImageSource的),然后施放此作为BitmapImage的。

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.

我的code是如下:

ImageSource source = MyImage.Source;
BitmapImage image = (BitmapImage) source;

这基本上是相同的code作为链接的答案,但我得到以下运行时错误在第二行(这里我想投):

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):

无法转换型System.Windows.Media.Imaging.BitmapFrameDe code对象类型System.Windows.Media.Imaging.BitmapImage。

Unable to cast object of type 'System.Windows.Media.Imaging.BitmapFrameDecode' to type 'System.Windows.Media.Imaging.BitmapImage'.

的合乎逻辑的答案我的猜测是,这根本不可能做到,但连接被接受的答案,有好评和四个upvotes这是令人沮丧的。我使用Visual Studio 2012与.net 4.5,我试图编译对4.0,3.5和3.0,和我看到了同样的问题。

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.

我也尝试修罗的建议的此处,结果仅仅是空(如,每当我使用的的关键字,而不是铸造所产生的变量的值是null)。

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).

在我的XAML,我的形象的源头控制属性是 *。BMP 文件,我最终试图让这一个WriteableBitmap的,但我需要有一个BitmapImage的通入WriteableBitmap的构造函数。

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.

所以我的问题是,我究竟做错了什么?如何从一个ImageSource的转换为BitmapImage的?

So my question is, what am I doing wrong? How do I convert from an ImageSource to a BitmapImage?

推荐答案

三江源的评论者,你帮助我理解这个问题。

Thankyou to the commenters, you helped me understand the problem.

我最后走的是源代码属性我的XAML,并做了以下在窗口中加载事件,以确保在来源我的图像控制的财产的确是一个BitmapImage的:

I ended up taking the Source property out of my XAML, and doing the below in the Window Loaded event to ensure that the Source property of my image control was indeed a BitmapImage:

private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
    var image = new BitmapImage(new Uri("sample.bmp", UriKind.Relative));
    MyImage.Source = image;
}

显然,如果你这样做在XAML来代替,Source属性最终被一个 BitmapFrameDe code 默认对象。