积极答复者
wpf 获取image控件的图像

问题
答案
-
System.Windows.Media.Imaging.BitmapImage imageSOURCE = new System.Windows.Media.Imaging.BitmapImage();
imageSOURCE = (System.Windows.Media.Imaging.BitmapImage) Image.Source;
这种方法我试过,编译没错,但运行的时候总报错。是强制转换的问题。
用bitmapsource就可以解决问题了:
BitmapSource oldmap = (BitmapSource)nowimage.Source;
还是谢谢你了。呵呵。
勿以恶小而为之,勿以善小而不为- 已标记为答案 dut60 2009年9月1日 13:18
-
你好,
-->imageSOURCE = (System.Windows.Media.Imaging.BitmapImage) Image.Source;这种方法我试过,编译没错,但运行的时候总报错。是强制转换的问题
之所以把Image.Source转成BitmapImage会出现异常是因为他们在这种情况下不是可转换的,当然转换结果是null.
为什么呢?其实你只要用Image.Source.GetType方法看一下就知道了,是一个叫作BitmapFrameDecode的类型,这个类型的父类是BitmapFrame,再上去就是BitmapSource,所以你转换成类层次较高的BitmapSource是没有问题的,而转换成BitmapImage就有问题了.
为了更好的理解,我把这里面的类层次图贴出来看一看:ImageSource
BitmapSource
BitmapFrame
BitmapFrameDecode
BitmapImage你会看到,BitmapFrame和BitmapImage在类层次中是平极的,平级中的类转怎么转换成另一个类实例呢?所以只能往上级类(BitmapSource)转了.
谢谢.
Jim Zhou -MSFT- 已标记为答案 Jim Zhou - MSFTModerator 2009年9月3日 3:59
全部回复
-
(1) 图像替换:
如果图像存在磁盘上,只需要改变图像的路径就行了。
------------------------------
System.Windows.Media.Imaging.BitmapImage imageURI = new System.Windows.Media.Imaging.BitmapImage();
///图片A:
imageURI.BeginInit();
imageURI.UriSource = new Uri("pack://siteOfOrigin:,,,/A.jpg", UriKind.Absolute);
imageURI.EndInit();
Image.Source = imageURI;
///图片B:
imageURI.BeginInit();
imageURI.UriSource = new Uri("pack://siteOfOrigin:,,,/B.jpg", UriKind.Absolute);
imageURI.EndInit();
Image.Source = imageURI;
==============================
(2) 获取图像:
Image.Source 就是图像的内容。
------------------------------
System.Windows.Media.Imaging.BitmapImage imageSOURCE = new System.Windows.Media.Imaging.BitmapImage();
imageSOURCE = (System.Windows.Media.Imaging.BitmapImage) Image.Source; -
System.Windows.Media.Imaging.BitmapImage imageSOURCE = new System.Windows.Media.Imaging.BitmapImage();
imageSOURCE = (System.Windows.Media.Imaging.BitmapImage) Image.Source;
这种方法我试过,编译没错,但运行的时候总报错。是强制转换的问题。
用bitmapsource就可以解决问题了:
BitmapSource oldmap = (BitmapSource)nowimage.Source;
还是谢谢你了。呵呵。
勿以恶小而为之,勿以善小而不为- 已标记为答案 dut60 2009年9月1日 13:18
-
你好,
-->imageSOURCE = (System.Windows.Media.Imaging.BitmapImage) Image.Source;这种方法我试过,编译没错,但运行的时候总报错。是强制转换的问题
之所以把Image.Source转成BitmapImage会出现异常是因为他们在这种情况下不是可转换的,当然转换结果是null.
为什么呢?其实你只要用Image.Source.GetType方法看一下就知道了,是一个叫作BitmapFrameDecode的类型,这个类型的父类是BitmapFrame,再上去就是BitmapSource,所以你转换成类层次较高的BitmapSource是没有问题的,而转换成BitmapImage就有问题了.
为了更好的理解,我把这里面的类层次图贴出来看一看:ImageSource
BitmapSource
BitmapFrame
BitmapFrameDecode
BitmapImage你会看到,BitmapFrame和BitmapImage在类层次中是平极的,平级中的类转怎么转换成另一个类实例呢?所以只能往上级类(BitmapSource)转了.
谢谢.
Jim Zhou -MSFT- 已标记为答案 Jim Zhou - MSFTModerator 2009年9月3日 3:59