我的 Silverlight 4 OOB 应用程序中有这个小功能,可以从扫描仪获取图像:
public static BitmapImage GetImageFromScanner()
{
try
{
using (dynamic CommonDialog = AutomationFactory.CreateObject("WIA.CommonDialog"))
{
//Param meanings: (scanner, black and white, maximize quality)
dynamic imageFile = CommonDialog.ShowAcquireImage(1, 2, 131072);
if (imageFile != null)
{
return (BitmapImage)imageFile;
}
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
if (ex.ErrorCode == -2145320939)
{
MessageBox.Show("Could not find an attached scanner.", "Scanner Error", MessageBoxButton.OK);
}
else if (ex.ErrorCode == -2145320957)
{
MessageBox.Show("There is no paper in the scanner.", "Scanner Error", MessageBoxButton.OK);
}
}
return null;
}
我希望该函数返回 BitmapImage 但我不确定如何转换动态类型。如果不是动态的,我什至不确定 imageFile 会是什么类型。上述方法返回以下异常:
Unable to cast object of type 'System.Runtime.InteropServices.Automation.AutomationMetaObjectProvider' to type 'System.Windows.Media.Imaging.BitmapImage'.
有人可以提供指导吗?我不确定这是否是关于 dynamic 关键字或 AutomationFactory 的问题,因为它们对我来说都是新的。:/
编辑:
我知道这是一张图片,因为如果我这样做:
string filePath = string.Format("c:\\{0}.jpg", Guid.NewGuid());
imageFile.SaveFile(filePath);
MessageBox.Show(string.Format("Saved {0}", filePath));
它将扫描的文档保存为 jpg。我试图弄清楚 .NET 框架中的哪些对象具有 SaveFile() 方法,并且似乎有很多。