Асинхронное получение изображений от TWAIN сканера
В этом разделе
VintaSoft Twain .NET SDK позволяет получать изображения с TWAIN сканера асинхронно.
Вот список необходимых действий для асинхронного получения изображений:
- Откройте менеджер устройств TWAIN.
- Выберите устройство TWAIN.
- Подпишитесь на события TWAIN устройства: Vintasoft.Twain.Device.ImageAcquired, Vintasoft.Twain.Device.ScanFinished и т.д.
- Откройте устройство TWAIN.
- Установите параметры сканирования.
- Запустите процесс получения асинхронных данных.
- Получите изображения по одному при наступлении события Vintasoft.Twain.Device.ImageAcquired.
- Остановите процесс получения изображения при возникновении события Vintasoft.Twain.Device.ScanCompleted.
Вот пример, который демонстрирует, как асинхронно сканировать изображения, используя пользовательский интерфейс TWAIN сканера, и сохранять отсканированные изображения в многостраничный файл TIFF:
namespace TwainExamples_CSharp
{
public partial class ScanAsynchronouslyDemoForm : System.Windows.Forms.Form
{
#region Fields
/// <summary>
/// TWAIN device manager.
/// </summary>
Vintasoft.Twain.DeviceManager _deviceManager;
#endregion
#region Constructors
public ScanAsynchronouslyDemoForm()
{
InitializeComponent();
// create and open device manager
_deviceManager = new Vintasoft.Twain.DeviceManager(this);
_deviceManager.Open();
}
#endregion
#region Methods
/// <summary>
/// Starts the image acquisition from scanner.
/// </summary>
private void startImageAcquisitionButton_Click(object sender, System.EventArgs e)
{
Vintasoft.Twain.Device device = null;
try
{
// select the default device
_deviceManager.ShowDefaultDeviceSelectionDialog();
// get reference to the default device
device = _deviceManager.DefaultDevice;
// if device is not found
if (device == null)
return;
// subscribe to the device events
SubscribeToDeviceEvents(device);
// set Memory transfer mode
device.TransferMode = Vintasoft.Twain.TransferMode.Memory;
// enable UI
device.ShowUI = true;
// open the device
device.Open();
// specify that black-white images must be acquired
device.PixelType = Vintasoft.Twain.PixelType.BW;
// specify the threshold for acquired images
device.Threshold = 128;
// set the inches as unit of measure
device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches;
device.Resolution = new Vintasoft.Twain.Resolution(300f, 300f);
// acquire images asynchronously
device.Acquire();
}
catch (Vintasoft.Twain.TwainException ex)
{
// if device is found
if (device != null)
{
// if device is opened
if (device.State >= Vintasoft.Twain.DeviceState.Opened)
// close the device
device.Close();
// unsubscribe from device events
UnsubscribeFromDeviceEvents(device);
}
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
/// <summary>
/// Image acquisition is in progress.
/// </summary>
private void device_ImageAcquiringProgress(
object sender,
Vintasoft.Twain.ImageAcquiringProgressEventArgs e)
{
// update progress bar
progressBar1.Value = e.Progress;
}
/// <summary>
/// Image is acquired.
/// </summary>
private void device_ImageAcquired(object sender, Vintasoft.Twain.ImageAcquiredEventArgs e)
{
// dispose image stored in the picture box
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
pictureBox1.Image = null;
}
// show acquired image in the picture box
pictureBox1.Image = e.Image.GetAsBitmap(true);
// add the acquired image to a TIFF file
e.Image.Save(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "multipage.tif"));
// dispose the acquired image
e.Image.Dispose();
}
/// <summary>
/// Scan is completed.
/// </summary>
private void device_ScanCompleted(object sender, System.EventArgs e)
{
System.Windows.Forms.MessageBox.Show("Scan is competed.");
}
/// <summary>
/// Scan is canceled.
/// </summary>
private void device_ScanCanceled(object sender, System.EventArgs e)
{
System.Windows.Forms.MessageBox.Show("Scan is canceled.");
}
/// <summary>
/// Scan is failed.
/// </summary>
private void device_ScanFailed(object sender, Vintasoft.Twain.ScanFailedEventArgs e)
{
System.Windows.Forms.MessageBox.Show(string.Format("Scan is failed: {0}", e.ErrorString));
}
/// <summary>
/// User interface of device is closed.
/// </summary>
private void device_UserInterfaceClosed(object sender, System.EventArgs e)
{
System.Windows.Forms.MessageBox.Show("User Interface is closed.");
}
/// <summary>
/// Scan is finished.
/// </summary>
private void device_ScanFinished(object sender, System.EventArgs e)
{
Vintasoft.Twain.Device device = (Vintasoft.Twain.Device)sender;
// unsubscribe from device events
UnsubscribeFromDeviceEvents(device);
// if device is not closed
if (device.State != Vintasoft.Twain.DeviceState.Closed)
// close the device
device.Close();
System.Windows.Forms.MessageBox.Show("Scan is finished.");
}
/// <summary>
/// Subscribes to the device events.
/// </summary>
private void SubscribeToDeviceEvents(Vintasoft.Twain.Device device)
{
device.ImageAcquiringProgress += new System.EventHandler<Vintasoft.Twain.ImageAcquiringProgressEventArgs>(device_ImageAcquiringProgress);
device.ImageAcquired += new System.EventHandler<Vintasoft.Twain.ImageAcquiredEventArgs>(device_ImageAcquired);
device.ScanCompleted += new System.EventHandler(device_ScanCompleted);
device.ScanCanceled += new System.EventHandler(device_ScanCanceled);
device.ScanFailed += new System.EventHandler<Vintasoft.Twain.ScanFailedEventArgs>(device_ScanFailed);
device.UserInterfaceClosed += new System.EventHandler(device_UserInterfaceClosed);
device.ScanFinished += new System.EventHandler(device_ScanFinished);
}
/// <summary>
/// Unsubscribes from the device events.
/// </summary>
private void UnsubscribeFromDeviceEvents(Vintasoft.Twain.Device device)
{
device.ImageAcquiringProgress -= new System.EventHandler<Vintasoft.Twain.ImageAcquiringProgressEventArgs>(device_ImageAcquiringProgress);
device.ImageAcquired -= new System.EventHandler<Vintasoft.Twain.ImageAcquiredEventArgs>(device_ImageAcquired);
device.ScanCompleted -= new System.EventHandler(device_ScanCompleted);
device.ScanCanceled -= new System.EventHandler(device_ScanCanceled);
device.ScanFailed -= new System.EventHandler<Vintasoft.Twain.ScanFailedEventArgs>(device_ScanFailed);
device.UserInterfaceClosed -= new System.EventHandler(device_UserInterfaceClosed);
device.ScanFinished -= new System.EventHandler(device_ScanFinished);
}
#endregion
}
}
Partial Public Class ScanAsynchronouslyDemoForm
Inherits Form
#Region "Fields"
''' <summary>
''' TWAIN device manager.
''' </summary>
Private _deviceManager As Vintasoft.Twain.DeviceManager
#End Region
#Region "Constructors"
Public Sub New()
InitializeComponent()
' create and open device manager
_deviceManager = New Vintasoft.Twain.DeviceManager(Me)
_deviceManager.Open()
End Sub
#End Region
#Region "Methods"
''' <summary>
''' Starts the image acquisition from scanner.
''' </summary>
Private Sub startImageAcquisitionButton_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim device As Vintasoft.Twain.Device = Nothing
Try
' select the default device
_deviceManager.ShowDefaultDeviceSelectionDialog()
' get reference to the default device
device = _deviceManager.DefaultDevice
' if device is not found
If device Is Nothing Then
Exit Sub
End If
' subscribe to the device events
SubscribeToDeviceEvents(device)
' set Memory transfer mode
device.TransferMode = Vintasoft.Twain.TransferMode.Memory
' enable UI
device.ShowUI = True
' open the device
device.Open()
' specify that black-white images must be acquired
device.PixelType = Vintasoft.Twain.PixelType.BW
' specify the threshold for acquired images
device.Threshold = 128
' set the inches as unit of measure
device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches
device.Resolution = New Vintasoft.Twain.Resolution(300.0F, 300.0F)
' acquire images asynchronously
device.Acquire()
Catch ex As Vintasoft.Twain.TwainException
' if device is found
If device IsNot Nothing Then
' if device is opened
If device.State >= Vintasoft.Twain.DeviceState.Opened Then
' close the device
device.Close()
End If
' unsubscribe from device events
UnsubscribeFromDeviceEvents(device)
End If
MsgBox(ex.Message)
End Try
End Sub
''' <summary>
''' Image acquisition is in progress.
''' </summary>
Private Sub device_ImageAcquiringProgress(ByVal sender As Object, ByVal e As Vintasoft.Twain.ImageAcquiringProgressEventArgs)
' update progress bar
progressBar1.Value = e.Progress
End Sub
''' <summary>
''' Image is acquired.
''' </summary>
Private Sub device_ImageAcquired(ByVal sender As Object, ByVal e As Vintasoft.Twain.ImageAcquiredEventArgs)
' dispose image stored in the picture box
If pictureBox1.Image IsNot Nothing Then
pictureBox1.Image.Dispose()
pictureBox1.Image = Nothing
End If
' show acquired image in the picture box
pictureBox1.Image = e.Image.GetAsBitmap(True)
' add the acquired image to a TIFF file
e.Image.Save(IO.Path.Combine(IO.Directory.GetCurrentDirectory(), "multipage.tif"))
' dispose the acquired image
e.Image.Dispose()
End Sub
''' <summary>
''' Scan is completed.
''' </summary>
Private Sub device_ScanCompleted(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("Scan is competed.")
End Sub
''' <summary>
''' Scan is canceled.
''' </summary>
Private Sub device_ScanCanceled(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("Scan is canceled.")
End Sub
''' <summary>
''' Scan is failed.
''' </summary>
Private Sub device_ScanFailed(ByVal sender As Object, ByVal e As Vintasoft.Twain.ScanFailedEventArgs)
MessageBox.Show(String.Format("Scan is failed: {0}", e.ErrorString))
End Sub
''' <summary>
''' User interface of device is closed.
''' </summary>
Private Sub device_UserInterfaceClosed(ByVal sender As Object, ByVal e As EventArgs)
MessageBox.Show("User Interface is closed.")
End Sub
''' <summary>
''' Scan is finished.
''' </summary>
Private Sub device_ScanFinished(ByVal sender As Object, ByVal e As EventArgs)
Dim device1 As Vintasoft.Twain.Device = DirectCast(sender, Vintasoft.Twain.Device)
' unsubscribe from device events
UnsubscribeFromDeviceEvents(device1)
' if device is not closed
If device1.State <> Vintasoft.Twain.DeviceState.Closed Then
' close the device
device1.Close()
End If
MessageBox.Show("Scan is finished.")
End Sub
''' <summary>
''' Subscribes to the device events.
''' </summary>
Private Sub SubscribeToDeviceEvents(ByVal device As Vintasoft.Twain.Device)
AddHandler device.ImageAcquiringProgress, New EventHandler(Of Vintasoft.Twain.ImageAcquiringProgressEventArgs)(AddressOf device_ImageAcquiringProgress)
AddHandler device.ImageAcquired, New EventHandler(Of Vintasoft.Twain.ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
AddHandler device.ScanCompleted, New EventHandler(AddressOf device_ScanCompleted)
AddHandler device.ScanCanceled, New EventHandler(AddressOf device_ScanCanceled)
AddHandler device.ScanFailed, New EventHandler(Of Vintasoft.Twain.ScanFailedEventArgs)(AddressOf device_ScanFailed)
AddHandler device.UserInterfaceClosed, New EventHandler(AddressOf device_UserInterfaceClosed)
AddHandler device.ScanFinished, New EventHandler(AddressOf device_ScanFinished)
End Sub
''' <summary>
''' Unsubscribes from the device events.
''' </summary>
Private Sub UnsubscribeFromDeviceEvents(ByVal device As Vintasoft.Twain.Device)
RemoveHandler device.ImageAcquiringProgress, New EventHandler(Of Vintasoft.Twain.ImageAcquiringProgressEventArgs)(AddressOf device_ImageAcquiringProgress)
RemoveHandler device.ImageAcquired, New EventHandler(Of Vintasoft.Twain.ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
RemoveHandler device.ScanCompleted, New EventHandler(AddressOf device_ScanCompleted)
RemoveHandler device.ScanCanceled, New EventHandler(AddressOf device_ScanCanceled)
RemoveHandler device.ScanFailed, New EventHandler(Of Vintasoft.Twain.ScanFailedEventArgs)(AddressOf device_ScanFailed)
RemoveHandler device.UserInterfaceClosed, New EventHandler(AddressOf device_UserInterfaceClosed)
RemoveHandler device.ScanFinished, New EventHandler(AddressOf device_ScanFinished)
End Sub
#End Region
End Class