Получение изображений от TWAIN сканера непосредственно на диск
В этом разделе
Многие устройства сканирования TWAIN поддерживают режим передачи файлов и позволяют сохранять полученные изображения непосредственно на диск.
Режимы передачи, поддерживаемые устройством, можно получить с помощью метода Vintasoft.Twain.Device.GetSupportedTransferModes.
Все сканирующие устройства TWAIN могут сохранять полученные изображения в виде файлов BMP. Профессиональные устройства могут сохранять полученные изображения в виде файлов TIFF, JPEG, PDF и т.д.
Форматы файлов, поддерживаемые устройством, можно получить с помощью метода Vintasoft.Twain.Device.GetSupportedImageFileFormats.
Форматы сжатия файлов, поддерживаемые устройством, можно получить с помощью метода Vintasoft.Twain.Device.GetSupportedImageCompressions.
Вот пример, который демонстрирует, как сохранять отсканированные изображения непосредственно на диск в виде файлов JPEG с качеством изображения в 70%:
namespace TwainExamples_CSharp
{
public partial class ScanAsynchronouslyDirectlyToDiskDemoForm : System.Windows.Forms.Form
{
#region Fields
/// <summary>
/// TWAIN device manager.
/// </summary>
Vintasoft.Twain.DeviceManager _deviceManager;
/// <summary>
/// Path to directory where acquired images will be saved.
/// </summary>
string _directoryForImages = @"d:\images\";
/// <summary>
/// Index of acquired image.
/// </summary>
int _imageIndex;
#endregion
#region Constructors
public ScanAsynchronouslyDirectlyToDiskDemoForm()
{
InitializeComponent();
// create and open device manager
_deviceManager = new Vintasoft.Twain.DeviceManager(this);
_deviceManager.Open();
}
#endregion
#region Methods
/// <summary>
/// Scans images asynchronously.
/// </summary>
public void startImageAcquisitionButton_Click()
{
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 the File transfer mode
device.TransferMode = Vintasoft.Twain.TransferMode.File;
// disable UI
device.ShowUI = false;
// open the device
device.Open();
// specify that gray images must be acquired
device.PixelType = Vintasoft.Twain.PixelType.Gray;
// set the inches as unit of measure
device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches;
// set the desired resolution of acquired images
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 is acquiring.
/// </summary>
private void device_ImageAcquiring(object sender, Vintasoft.Twain.ImageAcquiringEventArgs e)
{
string fileExtension = "bmp";
switch (e.FileFormat)
{
case Vintasoft.Twain.TwainImageFileFormat.Tiff:
fileExtension = "tif";
break;
case Vintasoft.Twain.TwainImageFileFormat.Jpeg:
fileExtension = "jpg";
break;
}
e.Filename = System.IO.Path.Combine(_directoryForImages, string.Format("page{0}.{1}", _imageIndex, fileExtension));
}
/// <summary>
/// Image is acquired.
/// </summary>
private void device_ImageAcquired(object sender, Vintasoft.Twain.ImageAcquiredEventArgs e)
{
statusTextBox.Text += string.Format("Image is saved to file '{0}'{1}", System.IO.Path.GetFileName(e.Filename), System.Environment.NewLine);
_imageIndex++;
}
/// <summary>
/// Scan is completed.
/// </summary>
private void device_ScanCompleted(object sender, System.EventArgs e)
{
statusTextBox.Text += string.Format("Scan is completed{0}", System.Environment.NewLine);
}
/// <summary>
/// Scan is canceled.
/// </summary>
private void device_ScanCanceled(object sender, System.EventArgs e)
{
statusTextBox.Text += string.Format("Scan is canceled{0}", System.Environment.NewLine);
}
/// <summary>
/// Scan is failed.
/// </summary>
private void device_ScanFailed(object sender, Vintasoft.Twain.ScanFailedEventArgs e)
{
statusTextBox.Text += string.Format("Scan failed: {0}{1}", e.ErrorString, System.Environment.NewLine);
}
/// <summary>
/// User interface of device is closed.
/// </summary>
private void device_UserInterfaceClosed(object sender, System.EventArgs e)
{
statusTextBox.Text += string.Format("User Interface is closed{0}", System.Environment.NewLine);
}
/// <summary>
/// Scan is finished.
/// </summary>
private void device_ScanFinished(object sender, System.EventArgs e)
{
Vintasoft.Twain.Device device = sender as Vintasoft.Twain.Device;
if (device != null)
{
// unsubscribe from device events
UnsubscribeFromDeviceEvents(device);
// if device is not closed
if (device.State != Vintasoft.Twain.DeviceState.Closed)
// close the device
device.Close();
}
}
/// <summary>
/// Subscribes to the device events.
/// </summary>
private void SubscribeToDeviceEvents(Vintasoft.Twain.Device device)
{
device.ImageAcquiring += new System.EventHandler<Vintasoft.Twain.ImageAcquiringEventArgs>(device_ImageAcquiring);
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.ImageAcquiring -= new System.EventHandler<Vintasoft.Twain.ImageAcquiringEventArgs>(device_ImageAcquiring);
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 ScanAsynchronouslyDirectlyToDiskDemoForm
Inherits Form
#Region "Fields"
''' <summary>
''' TWAIN device manager.
''' </summary>
Private _deviceManager As Vintasoft.Twain.DeviceManager
''' <summary>
''' Path to directory where acquired images will be saved.
''' </summary>
Private _directoryForImages As String = "d:\images\"
''' <summary>
''' Index of acquired image.
''' </summary>
Private _imageIndex As Integer
#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>
''' Scans the images asynchronously.
''' </summary>
Public Sub startImageAcquisitionButton_Click()
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 the File transfer mode
device.TransferMode = Vintasoft.Twain.TransferMode.File
' disable UI
device.ShowUI = False
' open the device
device.Open()
' specify that gray images must be acquired
device.PixelType = Vintasoft.Twain.PixelType.Gray
' set the inches as unit of measure
device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches
' set the desired resolution of acquired images
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 is acquiring.
''' </summary>
Private Sub device_ImageAcquiring(ByVal sender As Object, ByVal e As Vintasoft.Twain.ImageAcquiringEventArgs)
Dim fileExtension As String = "bmp"
Select Case e.FileFormat
Case Vintasoft.Twain.TwainImageFileFormat.Tiff
fileExtension = "tif"
Exit Select
Case Vintasoft.Twain.TwainImageFileFormat.Jpeg
fileExtension = "jpg"
Exit Select
End Select
e.Filename = IO.Path.Combine(_directoryForImages, String.Format("page{0}.{1}", _imageIndex, fileExtension))
End Sub
''' <summary>
''' Image is acquired.
''' </summary>
Private Sub device_ImageAcquired(ByVal sender As Object, ByVal e As Vintasoft.Twain.ImageAcquiredEventArgs)
statusTextBox.Text += String.Format("Image is saved to file '{0}'{1}", IO.Path.GetFileName(e.Filename), Environment.NewLine)
_imageIndex += 1
End Sub
''' <summary>
''' Scan is completed.
''' </summary>
Private Sub device_ScanCompleted(ByVal sender As Object, ByVal e As EventArgs)
statusTextBox.Text += String.Format("Scan is completed{0}", Environment.NewLine)
End Sub
''' <summary>
''' Scan is canceled.
''' </summary>
Private Sub device_ScanCanceled(ByVal sender As Object, ByVal e As EventArgs)
statusTextBox.Text += String.Format("Scan is canceled{0}", Environment.NewLine)
End Sub
''' <summary>
''' Scan is failed.
''' </summary>
Private Sub device_ScanFailed(ByVal sender As Object, ByVal e As Vintasoft.Twain.ScanFailedEventArgs)
statusTextBox.Text += String.Format("Scan failed: {0}{1}", e.ErrorString, Environment.NewLine)
End Sub
''' <summary>
''' User interface of device is closed.
''' </summary>
Private Sub device_UserInterfaceClosed(ByVal sender As Object, ByVal e As EventArgs)
statusTextBox.Text += String.Format("User Interface is closed{0}", Environment.NewLine)
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
statusTextBox.Text += String.Format("Scan is finished{0}", Environment.NewLine)
End Sub
''' <summary>
''' Subscribes to the device events.
''' </summary>
Private Sub SubscribeToDeviceEvents(ByVal device As Vintasoft.Twain.Device)
AddHandler device.ImageAcquiring, New EventHandler(Of Vintasoft.Twain.ImageAcquiringEventArgs)(AddressOf device_ImageAcquiring)
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.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.ImageAcquiring, New EventHandler(Of Vintasoft.Twain.ImageAcquiringEventArgs)(AddressOf device_ImageAcquiring)
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.ScanFinished, New EventHandler(AddressOf device_ScanFinished)
End Sub
#End Region
End Class