我们有时候需要使用扫描仪来把纸质文档转换成电子文档用于保存。这篇文章介绍如何创建一个简单的应用,把文件扫描成图片,保存到Google的云服务中。
参考原文:
How to Upload Scanned Images to Google Drive With Dynamic .NET TWAIN
准备工作
下载安装 Dynamic .NET TWAIN SDK。
如果没有扫描仪,可以下载安装虚拟扫描仪。
扫描文件
在Visual Studio中创建一个WinForms的工程。
在引用中添加DynamicDotNetTWAIN.dll。
创建界面:左侧的显示区域是DynamicDotNetTWAIN控件。
获取设备:
dynamicDotNetTwain.OpenSourceManager();
for (lngNum = 0; lngNum < dynamicDotNetTwain.SourceCount; lngNum++)
{
cmbSource.Items.Add(dynamicDotNetTwain.SourceNameItems(Convert.ToInt16(lngNum)));
}
获取图像,显示在控件中:
try
{
dynamicDotNetTwain.SelectSourceByIndex(Convert.ToInt16(cmbSource.SelectedIndex));
dynamicDotNetTwain.IfShowUI = false;
dynamicDotNetTwain.OpenSource();
dynamicDotNetTwain.IfDisableSourceAfterAcquire = true;
dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_RGB;
dynamicDotNetTwain.BitDepth = 24;
dynamicDotNetTwain.Resolution = 300;
dynamicDotNetTwain.AcquireImage();
}
catch (Dynamsoft.DotNet.TWAIN.TwainException exp)
{
String errorstr = "";
errorstr += "Error " + exp.Code + "\r\n" + "Description: " + exp.Message + "\r\nPosition: " + exp.TargetSite + "\r\nHelp: " + exp.HelpLink + "\r\n";
MessageBox.Show(errorstr);
}
上传到Google Drive
在Google开发者控制中心创建一个新的工程。
启用Drive API。
选择Credentials来创建一个新的客户端ID。
在Visual Studio中安装NuGet Package Manager (Tools -> Extensions and Updates)。
运行Package Manager Console,输入Install-Package Google.Apis.Drive.v2来安装Drive API NuGet package。成功之后引用中多了Google的部分。
添加上传代码:
Image image = dynamicDotNetTwain.GetImage(dynamicDotNetTwain.CurrentImageIndexInBuffer); // Get image data from memory
string mimeType = "image/png";
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = " "CLIENT_ID_HERE",
ClientSecret = "CLIENT_SECRET_HERE",
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ScanUpload",
});
File body = new File();
body.Title = mFileTitle;
body.Description = "image";
body.MimeType = mimeType;
ImageConverter imageConverter = new ImageConverter();
byte[] byteArray = (byte[])imageConverter.ConvertTo(image, typeof(byte[])); // convert image to byte
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
request.Upload();
运行程序。
上传之后,打开Google Drive查看。
源码
https://github.com/DynamsoftRD/CloudScanner
git clone https://github.com/DynamsoftRD/CloudScanner.git
参考原文
How to Upload Scanned Images to Google Drive With Dynamic .NET TWAIN
来源:oschina
链接:https://my.oschina.net/u/1187419/blog/232835