佳能 TWAIN 扫描仪卡在 'Warming up' 分钟
Canon TWAIN scanner stuck on 'Warming up' for minutes
我正在尝试使用 NTwain 库从 C# 连接兼容 TWAIN 的多功能打印机和扫描仪,佳能 Pixma MG5750。我正在编写一个程序来将图像扫描到 Image
对象中。
扫描仪在扫描图像前需要预热;这样做时会显示以下弹出窗口:
此过程完成后,将开始扫描文档。
虽然该程序确实有效,但问题是此预热过程有时会无缘无故地花费太长时间,最多可达几分钟。使用佳能自己的应用 IJ Scan Utility 时,此问题从未发生,它使用 TWAIN 并显示相同的对话框,但仅显示几秒钟。
我可以使用 TWAIN 功能来提高预热过程的速度吗?我试过更改 ICapXResolution
和 ICapYResolution
,但这些只会提高预热后实际扫描的速度,不会影响预热本身。
我的程序如下图所示。请注意,它是一个控制台应用程序,因此使用 ThreadPool
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NTwain;
using NTwain.Data;
using System.Drawing;
using System.Threading;
namespace TwainExample
{
class Program
{
[STAThread]
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(o => TwainWork());
Console.ReadLine();
}
static void TwainWork()
{
var identity = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetEntryAssembly());
var twain = new TwainSession(identity);
twain.Open();
twain.DataTransferred += (s, e) =>
{
var stream = e.GetNativeImageStream();
var image = Image.FromStream(stream);
// Do things with the image...
};
var source = twain.First();
Console.WriteLine($"Scanning from {source.Name}...");
var openCode = source.Open();
Console.WriteLine($"Open: {openCode}");
source.Enable(SourceEnableMode.NoUI, false, IntPtr.Zero);
}
}
}
它输出:
Scanning from Canon MG5700 series Network...
Open: Success
我不久前为扫描仪构建了一个 Web 服务(也使用 TWAIN)托管在带有 OWIN 的控制台应用程序中。我想巧合的是,我从来没有想过采用与您相同的方法,因为我只是将它构建为一个普通的网络应用程序,当我注意到类似的问题时,我发现了一些将扫描过程本身锁定到单个线程的示例。
基本上,我认为您不需要 [STAThread]
属性或 ThreadPool。好吧,如果您希望您的控制台应用程序保持响应,您可以保留 ThreadPool。
如果我没记错的话,您还需要设备 ID 来获取正确的数据源。我已经调整了我的一些代码(有很多与设置扫描配置文件相关的部分,现在非常天真地内联),试试这个(有或没有 ThreadPool):
class Program
{
static void Main(string[] args)
{
var scanner = new TwainScanner();
scanner.Scan("your device id");
Console.ReadLine();
}
}
public sealed class CustomTwainSession : TwainSession
{
private Exception _error;
private bool _cancel;
private ReturnCode _returnCode;
private DataSource _dataSource;
private Bitmap _image;
public Exception Error => _error;
public bool IsSuccess => _error == null && _returnCode == ReturnCode.Success;
public Bitmap Bitmap => _image;
static CustomTwainSession()
{
PlatformInfo.Current.PreferNewDSM = false;
}
public CustomTwainSession(): base(TwainScanner.TwainAppId)
{
_cancel = false;
TransferReady += OnTransferReady;
DataTransferred += OnDataTransferred;
TransferError += OnTransferError;
}
public void Start(string deviceId)
{
try
{
_returnCode = Open();
if (_returnCode == ReturnCode.Success)
{
_dataSource = this.FirstOrDefault(x => x.Name == deviceId);
if (_dataSource != null)
{
_returnCode = _dataSource.Open();
if (_returnCode == ReturnCode.Success)
{
_returnCode = _dataSource.Enable(SourceEnableMode.NoUI, false, IntPtr.Zero);
}
}
else
{
throw new Exception($"Device {deviceId} not found.");
}
}
}
catch (Exception ex)
{
_error = ex;
}
if (_dataSource != null && IsSourceOpen)
{
_dataSource.Close();
}
if (IsDsmOpen)
{
Close();
}
}
private void OnTransferReady(object sender, TransferReadyEventArgs e)
{
_dataSource.Capabilities.CapFeederEnabled.SetValue(BoolType.False);
_dataSource.Capabilities.CapDuplexEnabled.SetValue(BoolType.False);
_dataSource.Capabilities.ICapPixelType.SetValue(PixelType.RGB);
_dataSource.Capabilities.ICapUnits.SetValue(Unit.Inches);
TWImageLayout imageLayout;
_dataSource.DGImage.ImageLayout.Get(out imageLayout);
imageLayout.Frame = new TWFrame
{
Left = 0,
Right = 210 * 0.393701f,
Top = 0,
Bottom = 297 * 0.393701f
};
_dataSource.DGImage.ImageLayout.Set(imageLayout);
_dataSource.Capabilities.ICapXResolution.SetValue(150);
_dataSource.Capabilities.ICapYResolution.SetValue(150);
if (_cancel)
{
e.CancelAll = true;
}
}
private void OnDataTransferred(object sender, DataTransferredEventArgs e)
{
using (var output = Image.FromStream(e.GetNativeImageStream()))
{
_image = new Bitmap(output);
}
}
private void OnTransferError(object sender, TransferErrorEventArgs e)
{
_error = e.Exception;
_cancel = true;
}
public void Dispose()
{
_image.Dispose();
}
}
public sealed class TwainScanner
{
public static TWIdentity TwainAppId { get; }
private static CustomTwainSession Session { get; set; }
static volatile object _locker = new object();
static TwainScanner()
{
TwainAppId = TWIdentity.CreateFromAssembly(DataGroups.Image | DataGroups.Control, Assembly.GetEntryAssembly());
}
public Bitmap Scan(string deviceId)
{
bool lockWasTaken = false;
try
{
if (Monitor.TryEnter(_locker))
{
lockWasTaken = true;
if (Session != null)
{
Session.Dispose();
Session = null;
}
Session = new CustomTwainSession();
Session.Start(deviceId);
return Session.Bitmap;
}
else
{
return null;
}
}
finally
{
if (lockWasTaken)
{
Monitor.Exit(_locker);
}
}
}
}
我可能没有注意到,这是几年前的事了,当时我对线程还不是很了解。我可能会采取不同的做法,但现在我无法用实际的扫描仪对其进行测试。这只是我的扫描逻辑的锁定机制,我知道它解决了无响应问题。
其他人可以随意在这种特定方法中找出漏洞;我知道这并不理想:)
我的一些建议
检查TwainSession是否实现了IDisposable,如果实现了,用"using"括起来。
正在向 twain.DataTransferred 添加处理程序但未删除,将 lambda 表达式提取到它自己的方法中,然后添加一行以删除处理程序。
修复起来比我想象的要简单得多!
我的 Canon 多功能机将两台设备暴露给 Windows。在我的机器上,它们是:
- 佳能MG5700系列网络
- WIA-MG5700系列_C6CA27000000
使用WIA设备,而不是佳能设备。 WIA 设备几乎立即预热!
只要您使用 WIA 设备,Fred Kleuver 发布的代码就可以完美地进行扫描;使用佳能时它似乎崩溃了。
我正在尝试使用 NTwain 库从 C# 连接兼容 TWAIN 的多功能打印机和扫描仪,佳能 Pixma MG5750。我正在编写一个程序来将图像扫描到 Image
对象中。
扫描仪在扫描图像前需要预热;这样做时会显示以下弹出窗口:
此过程完成后,将开始扫描文档。
虽然该程序确实有效,但问题是此预热过程有时会无缘无故地花费太长时间,最多可达几分钟。使用佳能自己的应用 IJ Scan Utility 时,此问题从未发生,它使用 TWAIN 并显示相同的对话框,但仅显示几秒钟。
我可以使用 TWAIN 功能来提高预热过程的速度吗?我试过更改 ICapXResolution
和 ICapYResolution
,但这些只会提高预热后实际扫描的速度,不会影响预热本身。
我的程序如下图所示。请注意,它是一个控制台应用程序,因此使用 ThreadPool
.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NTwain;
using NTwain.Data;
using System.Drawing;
using System.Threading;
namespace TwainExample
{
class Program
{
[STAThread]
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(o => TwainWork());
Console.ReadLine();
}
static void TwainWork()
{
var identity = TWIdentity.CreateFromAssembly(DataGroups.Image, Assembly.GetEntryAssembly());
var twain = new TwainSession(identity);
twain.Open();
twain.DataTransferred += (s, e) =>
{
var stream = e.GetNativeImageStream();
var image = Image.FromStream(stream);
// Do things with the image...
};
var source = twain.First();
Console.WriteLine($"Scanning from {source.Name}...");
var openCode = source.Open();
Console.WriteLine($"Open: {openCode}");
source.Enable(SourceEnableMode.NoUI, false, IntPtr.Zero);
}
}
}
它输出:
Scanning from Canon MG5700 series Network...
Open: Success
我不久前为扫描仪构建了一个 Web 服务(也使用 TWAIN)托管在带有 OWIN 的控制台应用程序中。我想巧合的是,我从来没有想过采用与您相同的方法,因为我只是将它构建为一个普通的网络应用程序,当我注意到类似的问题时,我发现了一些将扫描过程本身锁定到单个线程的示例。
基本上,我认为您不需要 [STAThread]
属性或 ThreadPool。好吧,如果您希望您的控制台应用程序保持响应,您可以保留 ThreadPool。
如果我没记错的话,您还需要设备 ID 来获取正确的数据源。我已经调整了我的一些代码(有很多与设置扫描配置文件相关的部分,现在非常天真地内联),试试这个(有或没有 ThreadPool):
class Program
{
static void Main(string[] args)
{
var scanner = new TwainScanner();
scanner.Scan("your device id");
Console.ReadLine();
}
}
public sealed class CustomTwainSession : TwainSession
{
private Exception _error;
private bool _cancel;
private ReturnCode _returnCode;
private DataSource _dataSource;
private Bitmap _image;
public Exception Error => _error;
public bool IsSuccess => _error == null && _returnCode == ReturnCode.Success;
public Bitmap Bitmap => _image;
static CustomTwainSession()
{
PlatformInfo.Current.PreferNewDSM = false;
}
public CustomTwainSession(): base(TwainScanner.TwainAppId)
{
_cancel = false;
TransferReady += OnTransferReady;
DataTransferred += OnDataTransferred;
TransferError += OnTransferError;
}
public void Start(string deviceId)
{
try
{
_returnCode = Open();
if (_returnCode == ReturnCode.Success)
{
_dataSource = this.FirstOrDefault(x => x.Name == deviceId);
if (_dataSource != null)
{
_returnCode = _dataSource.Open();
if (_returnCode == ReturnCode.Success)
{
_returnCode = _dataSource.Enable(SourceEnableMode.NoUI, false, IntPtr.Zero);
}
}
else
{
throw new Exception($"Device {deviceId} not found.");
}
}
}
catch (Exception ex)
{
_error = ex;
}
if (_dataSource != null && IsSourceOpen)
{
_dataSource.Close();
}
if (IsDsmOpen)
{
Close();
}
}
private void OnTransferReady(object sender, TransferReadyEventArgs e)
{
_dataSource.Capabilities.CapFeederEnabled.SetValue(BoolType.False);
_dataSource.Capabilities.CapDuplexEnabled.SetValue(BoolType.False);
_dataSource.Capabilities.ICapPixelType.SetValue(PixelType.RGB);
_dataSource.Capabilities.ICapUnits.SetValue(Unit.Inches);
TWImageLayout imageLayout;
_dataSource.DGImage.ImageLayout.Get(out imageLayout);
imageLayout.Frame = new TWFrame
{
Left = 0,
Right = 210 * 0.393701f,
Top = 0,
Bottom = 297 * 0.393701f
};
_dataSource.DGImage.ImageLayout.Set(imageLayout);
_dataSource.Capabilities.ICapXResolution.SetValue(150);
_dataSource.Capabilities.ICapYResolution.SetValue(150);
if (_cancel)
{
e.CancelAll = true;
}
}
private void OnDataTransferred(object sender, DataTransferredEventArgs e)
{
using (var output = Image.FromStream(e.GetNativeImageStream()))
{
_image = new Bitmap(output);
}
}
private void OnTransferError(object sender, TransferErrorEventArgs e)
{
_error = e.Exception;
_cancel = true;
}
public void Dispose()
{
_image.Dispose();
}
}
public sealed class TwainScanner
{
public static TWIdentity TwainAppId { get; }
private static CustomTwainSession Session { get; set; }
static volatile object _locker = new object();
static TwainScanner()
{
TwainAppId = TWIdentity.CreateFromAssembly(DataGroups.Image | DataGroups.Control, Assembly.GetEntryAssembly());
}
public Bitmap Scan(string deviceId)
{
bool lockWasTaken = false;
try
{
if (Monitor.TryEnter(_locker))
{
lockWasTaken = true;
if (Session != null)
{
Session.Dispose();
Session = null;
}
Session = new CustomTwainSession();
Session.Start(deviceId);
return Session.Bitmap;
}
else
{
return null;
}
}
finally
{
if (lockWasTaken)
{
Monitor.Exit(_locker);
}
}
}
}
我可能没有注意到,这是几年前的事了,当时我对线程还不是很了解。我可能会采取不同的做法,但现在我无法用实际的扫描仪对其进行测试。这只是我的扫描逻辑的锁定机制,我知道它解决了无响应问题。
其他人可以随意在这种特定方法中找出漏洞;我知道这并不理想:)
我的一些建议
检查TwainSession是否实现了IDisposable,如果实现了,用"using"括起来。
正在向 twain.DataTransferred 添加处理程序但未删除,将 lambda 表达式提取到它自己的方法中,然后添加一行以删除处理程序。
修复起来比我想象的要简单得多!
我的 Canon 多功能机将两台设备暴露给 Windows。在我的机器上,它们是:
- 佳能MG5700系列网络
- WIA-MG5700系列_C6CA27000000
使用WIA设备,而不是佳能设备。 WIA 设备几乎立即预热!
只要您使用 WIA 设备,Fred Kleuver 发布的代码就可以完美地进行扫描;使用佳能时它似乎崩溃了。