【问题标题】:Porting image drawing code from WinForm to WPF [duplicate]将图像绘制代码从 WinForm 移植到 WPF [重复]
【发布时间】:2018-08-08 08:51:30
【问题描述】:

我在 WinForm 应用程序中做了一些原型设计,代码对我有用:

using System.Drawing;
using System.Drawing.Imaging;

......

Image img0 = null;
img0 = Image.FromFile(filename);
PropertyItem[] propItems = img0.PropertyItems;

但是,当我将它复制到 WPF 应用程序时,我在引用之间遇到错误和不兼容问题。

我尝试添加 .NET 引用 System.Drawing 和 System.Drawing.Imaging,但与 System.Windows.Control.Image 存在冲突。 任何人都可以建议如何重写上述代码以使其在 WPF 中工作。

【问题讨论】:

  • 倾向于说“从头开始”,而不是将 Winform 代码移植到 WPF。除非您管理(并且想要)host the respective winform control in WPF
  • 如果它是我同意 Fildor 的原型,请在 WPF 中从头开始重写它。如果您将其复制并粘贴到您的实际应用程序中,它从来都不是原型设计,但会带来原型代码通常存在的所有问题。
  • 重写这三行没有问题,但我找不到等效项,我通过提供文件名加载文件并获得对 PropertyItems 的即时访问。您能否建议 WPF 中 Image.FromFile 和 PropertyItem 的等效项。

标签: c# wpf winforms reference system.drawing


【解决方案1】:

每当你发现自己在处理类名冲突时,你可以设置一个 using 来指定你在使用该类时所谈论的命名空间:

using System.Drawing;
using System.Drawing.Imaging;
using Image = System.Drawing.Image;

OR,您可以在声明中明确定义命名空间:

System.Drawing.Image img0 = null;
img0 = System.Drawing.Image.FromFile(filename);

如果我知道我不会同时使用 Image(System.Drawing 和 System.Windows.Controls)类,我个人更喜欢第一种方法

现在,如果您尝试以编程方式创建 System.Windows.Controls.Image,请检查: Setting WPF image source in code

【讨论】:

  • 另一种选择是将 Image.FromFile 替换为等效项,但 System.Windows.Control 中的 Image 与 System.Drawing 中的 Image 不同,因此它没有 FromFile 方法。 WinForm 代码是获取 PropertyItems 值的一种简单方法。
  • 您到底想完成什么?您是否正在尝试创建动态图像控件?如果是这样,您需要使用新的 BitmapImage 对象设置 System.Windows.Controls.Image 的 ImageSource 属性
  • BitmapImage 没有 PropertyItems。
  • 小提示:不要使用Image.FromFile(path)。它只是 Bitmap 的构造函数,作为其不太具体的 Image 超类返回。没有理由不使用new Bitmap(path)
  • @Joe 所以你真正的问题是“如何使用 WPF 读取图像元数据”。 Which is already answered on SO..
猜你喜欢
  • 2014-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
  • 2011-08-12
相关资源
最近更新 更多