VintaSoft Twain .NET SDK 15.3: Руководство для .NET разработчика
В этом разделе
    Получение изображений от TWAIN сканера изображений непосредственно на диск
    В этом разделе
    Большинство TWAIN устройства поддерживают режим передачи File и позволяют сохранять отсканированные изображения непосредственно в файл.
    Режимы передачи, поддерживаемые устройством, можно получить с помощью метода Vintasoft.Twain.Device.GetSupportedTransferModes.

    TWAIN устройства всегда могут сохранять отсканированные изображения в виде файлов BMP. Профессиональные устройства могут сохранять отсканированные изображения в виде файлов TIFF, JPEG, PDF, ...
    Форматы файлов, поддерживаемые устройством, можно получить с помощью метода Vintasoft.Twain.Device.GetSupportedImageFileFormats.
    Форматы сжатия данных изображения, поддерживаемые устройством, можно получить с помощью метода Vintasoft.Twain.Device.GetSupportedImageCompressions.


    Вот C#/VB.NET код, который демонстрирует, как сохранять отсканированные изображения непосредственно на диск в виде файлов JPEG с качеством изображения в 70%:
    static bool _isScanningFinished;
    
    /// <summary>
    /// Index of acquired image.
    /// </summary>
    static int _imageIndex;
    
    
    /// <summary>
    /// Uses File tranfer for saving TWAIN acquired images directly to a file on disk.
    /// </summary>
    public static void UseFileTransferForAcquiringImagesFromTwainDevice()
    {
        _isScanningFinished = false;
    
        // create the device manager
        using (Vintasoft.Twain.DeviceManager deviceManager = new Vintasoft.Twain.DeviceManager())
        {
            deviceManager.IsTwain2Compatible = true;
            // open the device manager
            deviceManager.Open();
    
            // get the device
            Vintasoft.Twain.Device device = deviceManager.DefaultDevice;
            if (device == null)
                return;
    
            // subscribe to device events
            SubscribeToDeviceEvents(device);
    
            // disable device UI
            device.ShowUI = false;
            // set the File transfer mode
            device.TransferMode = Vintasoft.Twain.TransferMode.File;
    
            // open the device
            device.Open();
    
            // specify that grayscale images must be acquired
            device.PixelType = Vintasoft.Twain.PixelType.Gray;
            // set the inches as unit of measure
            device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches;
            device.Resolution = new Vintasoft.Twain.Resolution(300f, 300f);
    
            // run asynchronous image acqusition
            device.Acquire();
    
            // wait while feeder will be stopped
            while (!_isScanningFinished)
            {
                System.Windows.Forms.Application.DoEvents();
            }
    
            // unsubscribe from device events
            UnsubscribeFromDeviceEvents(device);
    
            // close the device
            device.Close();
        }
    }
    
    /// <summary>
    /// Image is acquiring.
    /// </summary>
    private static 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(@"d:\images\", string.Format("page{0}.{1}", _imageIndex, fileExtension));
    }
    
    /// <summary>
    /// Image is acquired.
    /// </summary>
    private static void device_ImageAcquired(object sender, Vintasoft.Twain.ImageAcquiredEventArgs e)
    {
        System.Console.WriteLine(string.Format("Image is saved to a file '{0}'.", System.IO.Path.GetFileName(e.Filename)));
        _imageIndex++;
    }
    
    /// <summary>
    /// Scan is completed.
    /// </summary>
    private static void device_ScanCompleted(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("Scan is completed.");
    }
    
    /// <summary>
    /// Scan is canceled.
    /// </summary>
    private static void device_ScanCanceled(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("Scan is canceled.");
    }
    
    /// <summary>
    /// Scan is failed.
    /// </summary>
    private static void device_ScanFailed(object sender, Vintasoft.Twain.ScanFailedEventArgs e)
    {
        System.Console.WriteLine(string.Format("Scan is failed: {0}.", e.ErrorString));
    }
    
    /// <summary>
    /// Scan is finished.
    /// </summary>
    private static 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.Console.WriteLine("Scan is finished.");
    
        _isScanningFinished = true;
    }
    
    /// <summary>
    /// Subscribes to the device events.
    /// </summary>
    private static 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.ScanFinished += new System.EventHandler(device_ScanFinished);
    }
    
    /// <summary>
    /// Unsubscribes from the device events.
    /// </summary>
    private static 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.ScanFinished -= new System.EventHandler(device_ScanFinished);
    }
    
    Shared _isScanningFinished As Boolean
    
    ''' <summary>
    ''' Index of acquired image.
    ''' </summary>
    Shared _imageIndex As Integer
    
    
    ''' <summary>
    ''' Uses File tranfer for saving TWAIN acquired images directly to a file on disk.
    ''' </summary>
    Public Shared Sub UseFileTransferForAcquiringImagesFromTwainDevice()
        _isScanningFinished = False
    
        ' create the device manager
        Using deviceManager As New Vintasoft.Twain.DeviceManager()
            deviceManager.IsTwain2Compatible = True
            ' open the device manager
            deviceManager.Open()
    
            ' get the device
            Dim device As Vintasoft.Twain.Device = deviceManager.DefaultDevice
            If device Is Nothing Then
                Return
            End If
    
            ' subscribe to device events
            SubscribeToDeviceEvents(device)
    
            ' disable device UI
            device.ShowUI = False
            ' set the File transfer mode
            device.TransferMode = Vintasoft.Twain.TransferMode.File
    
            ' open the device
            device.Open()
    
            ' specify that grayscale images must be acquired
            device.PixelType = Vintasoft.Twain.PixelType.Gray
            ' set the inches as unit of measure
            device.UnitOfMeasure = Vintasoft.Twain.UnitOfMeasure.Inches
            device.Resolution = New Vintasoft.Twain.Resolution(300.0F, 300.0F)
    
            ' run asynchronous image acqusition
            device.Acquire()
    
            ' wait while feeder will be stopped
            While Not _isScanningFinished
                System.Windows.Forms.Application.DoEvents()
            End While
    
            ' unsubscribe from device events
            UnsubscribeFromDeviceEvents(device)
    
            ' close the device
            device.Close()
        End Using
    End Sub
    
    ''' <summary>
    ''' Image is acquiring.
    ''' </summary>
    Private Shared Sub Device_ImageAcquiring(sender As Object, 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 = System.IO.Path.Combine("d:\images\", String.Format("page{0}.{1}", _imageIndex, fileExtension))
    End Sub
    
    ''' <summary>
    ''' Image is acquired.
    ''' </summary>
    Private Shared Sub device_ImageAcquired(sender As Object, e As Vintasoft.Twain.ImageAcquiredEventArgs)
        System.Console.WriteLine(String.Format("Image is saved to a file '{0}'.", System.IO.Path.GetFileName(e.Filename)))
        _imageIndex += 1
    End Sub
    
    ''' <summary>
    ''' Scan is completed.
    ''' </summary>
    Private Shared Sub device_ScanCompleted(sender As Object, e As System.EventArgs)
        System.Console.WriteLine("Scan is completed.")
    End Sub
    
    ''' <summary>
    ''' Scan is canceled.
    ''' </summary>
    Private Shared Sub device_ScanCanceled(sender As Object, e As System.EventArgs)
        System.Console.WriteLine("Scan is canceled.")
    End Sub
    
    ''' <summary>
    ''' Scan is failed.
    ''' </summary>
    Private Shared Sub device_ScanFailed(sender As Object, e As Vintasoft.Twain.ScanFailedEventArgs)
        System.Console.WriteLine(String.Format("Scan is failed: {0}.", e.ErrorString))
    End Sub
    
    ''' <summary>
    ''' Scan is finished.
    ''' </summary>
    Private Shared Sub device_ScanFinished(sender As Object, e As System.EventArgs)
        Dim device As Vintasoft.Twain.Device = DirectCast(sender, Vintasoft.Twain.Device)
    
        ' unsubscribe from device events
        UnsubscribeFromDeviceEvents(device)
    
        ' if device is not closed
        If device.State <> Vintasoft.Twain.DeviceState.Closed Then
            ' close the device
            device.Close()
        End If
    
        System.Console.WriteLine("Scan is finished.")
    
        _isScanningFinished = True
    End Sub
    
    ''' <summary>
    ''' Subscribes to the device events.
    ''' </summary>
    Private Shared Sub SubscribeToDeviceEvents(device As Vintasoft.Twain.Device)
        AddHandler device.ImageAcquiring, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiringEventArgs)(AddressOf Device_ImageAcquiring)
        AddHandler device.ImageAcquired, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
        AddHandler device.ScanCompleted, New System.EventHandler(AddressOf device_ScanCompleted)
        AddHandler device.ScanCanceled, New System.EventHandler(AddressOf device_ScanCanceled)
        AddHandler device.ScanFailed, New System.EventHandler(Of Vintasoft.Twain.ScanFailedEventArgs)(AddressOf device_ScanFailed)
        AddHandler device.ScanFinished, New System.EventHandler(AddressOf device_ScanFinished)
    End Sub
    
    ''' <summary>
    ''' Unsubscribes from the device events.
    ''' </summary>
    Private Shared Sub UnsubscribeFromDeviceEvents(device As Vintasoft.Twain.Device)
        RemoveHandler device.ImageAcquiring, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiringEventArgs)(AddressOf Device_ImageAcquiring)
        RemoveHandler device.ImageAcquired, New System.EventHandler(Of Vintasoft.Twain.ImageAcquiredEventArgs)(AddressOf device_ImageAcquired)
        RemoveHandler device.ScanCompleted, New System.EventHandler(AddressOf device_ScanCompleted)
        RemoveHandler device.ScanCanceled, New System.EventHandler(AddressOf device_ScanCanceled)
        RemoveHandler device.ScanFailed, New System.EventHandler(Of Vintasoft.Twain.ScanFailedEventArgs)(AddressOf device_ScanFailed)
        RemoveHandler device.ScanFinished, New System.EventHandler(AddressOf device_ScanFinished)
    End Sub