Acquire images from TWAIN scanner using console .NET application in Linux

Blog category: TWAIN.NETLinux

March 02, 2023

This article explains how to create a console .NET application and acquire images from TWAIN scanner in Ubuntu. For image acqusition from TWAIN scanner is used VintaSoft TWAIN .NET SDK.

Here are the steps to complete that task:
  1. Open Ubuntu desktop.

  2. Create a folder, which will store the files of .NET application. Let us create "Scan_Images" folder on current user's desktop and proceed to the folder.


  3. Open the console command terminal. This can be done choosing "Open in Terminal" item in context menu or pressing the key combination Ctrl+Alt+T.


  4. Call the command in terminal, which creates a project of new console .NET application:
    dotnet new console --framework net7.0
    



    The created project contains the project file "Scan_Images.csproj" and "Program.cs" file, which contains C# code of application. Close terminal.

  5. Open the project file "Scan_Images.csproj" in text editor and change the file text to the following text:
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net7.0</TargetFramework>
        <RootNamespace>ConsoleApp1</RootNamespace>
        <ImplicitUsings>enable</ImplicitUsings>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Vintasoft.Shared" Version="3.4.0.1" />
        <PackageReference Include="Vintasoft.Shared" Version="14.0.1.1" />
      </ItemGroup>
    
    </Project>
    



    The changed project references nuget-packages for VintaSoft TWAIN .NET SDK (Vintasoft.Shared.dll, Vintasoft.Twain.dll).

  6. Open the file "Program.cs" and change its code to the following C# code:
    using System;
    using System.IO;
    
    using Vintasoft.Twain;
    
    namespace ConsoleApp1
    {
        class Program
        {
    
            static void Main(string[] args)
            {
                Vintasoft.Twain.TwainGlobalSettings.Register("VintaSoft", "support@vintasoft.com", "2023-04-02", "...");
            
                try
                {
                    // create TWAIN device manager
                    using (DeviceManager deviceManager = new DeviceManager())
                    {
                        // open TWAIN device manager
                        if (!OpenDeviceManager(deviceManager))
                            return;
    
                        // select TWAIN device
                        Device device = SelectDevice(deviceManager);
                        // if device is not selected
                        if (device == null)
                            return;
    
                        // specify that device UI should not be shown
                        device.ShowUI = false;
                        // specify that image scanning progess UI should not be shown
                        device.ShowIndicators = false;
                        // specify that device must be disabled after image scan
                        device.DisableAfterAcquire = true;
    
                        // open the device
                        device.Open();
    
                        // set device parameters
                        device.TransferMode = TransferMode.Native;
                        device.PixelType = PixelType.BW;
                        device.XferCount = 1;
    
                        // create directory for TIFF file
                        string directoryForImages = Path.GetDirectoryName(Directory.GetCurrentDirectory());
                        directoryForImages = Path.Combine(directoryForImages, "Images");
                        if (!Directory.Exists(directoryForImages))
                            Directory.CreateDirectory(directoryForImages);
    
                        string multipageTiffFilename = Path.Combine(directoryForImages, "multipage.tif");
    
                        // acquire image(s) from the device
                        int imageIndex = 0;
                        AcquireModalState acquireModalState = AcquireModalState.None;
                        do
                        {
                            acquireModalState = device.AcquireModal();
                            switch (acquireModalState)
                            {
                                case AcquireModalState.ImageAcquired:
                                    // save acquired image to a file
                                    device.AcquiredImage.Save(multipageTiffFilename);
                                    // dispose an acquired image
                                    device.AcquiredImage.Dispose();
    
                                    Console.WriteLine(string.Format("Image{0} is saved.", imageIndex++));
                                    break;
    
                                case AcquireModalState.ScanCompleted:
                                    Console.WriteLine("Scan is completed.");
                                    break;
    
                                case AcquireModalState.ScanCanceled:
                                    Console.WriteLine("Scan is canceled.");
                                    break;
    
                                case AcquireModalState.ScanFailed:
                                    Console.WriteLine(string.Format("Scan is failed: {0}", device.ErrorString));
                                    break;
    
                                case AcquireModalState.UserInterfaceClosed:
                                    Console.WriteLine("User interface is closed.");
                                    break;
                            }
                        }
                        while (acquireModalState != AcquireModalState.None);
    
                        // close the device
                        device.Close();
    
                        // close the device manager
                        deviceManager.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
    
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }
    
            /// <summary>
            /// Opens the TWAIN device manager.
            /// </summary>
            /// <param name="deviceManager">Device manager.</param>
            /// <returns><b>True</b> - device manager is opened successfully; otherwise, <b>false</b>.</returns>
            private static bool OpenDeviceManager(DeviceManager deviceManager)
            {
                // try to use TWAIN device manager 2.x
                deviceManager.IsTwain2Compatible = true;
                // if TWAIN device manager 2.x is not available
                if (!deviceManager.IsTwainAvailable)
                {
                    Console.WriteLine("TWAIN device manager is not available.");
                    return false;
                }
    
                // open the device manager
                deviceManager.Open();
    
                return true;
            }
    
            /// <summary>
            /// Selects the TWAIN device.
            /// </summary>
            /// <param name="deviceManager">TWAIN device manager.</param>
            /// <returns>TWAIN device if device is selected; otherwiase, <b>null</b>.</returns>
            private static Device SelectDevice(DeviceManager deviceManager)
            {
                int deviceCount = deviceManager.Devices.Count;
                // if no devices are found in the system
                if (deviceCount == 0)
                {
                    Console.WriteLine("Devices are not found.");
                    return null;
                }
    
                Console.WriteLine("Device list:");
                for (int i = 0; i < deviceCount; i++)
                {
                    Console.WriteLine(string.Format("{0}. {1}", i + 1, deviceManager.Devices[i].Info.ProductName));
                }
    
                int deviceIndex = -1;
                while (deviceIndex < 0 || deviceIndex > deviceCount)
                {
                    Console.Write(string.Format("Please select device by entering the device number from '1' to '{0}' or press '0' to cancel: ", deviceCount));
                    deviceIndex = Console.ReadKey().KeyChar - '0';
                    Console.WriteLine();
                }
                Console.WriteLine();
    
                if (deviceIndex == 0)
                    return null;
    
                return deviceManager.Devices[deviceIndex - 1];
            }
    
        }
    }
    



    The application code outputs a list of available TWAIN scanners, allows to select TWAIN scanner, acquires black-white images from TWAIN scanner and saves scanned images to a multipage TIFF file.

  7. Get the code for using evaluation version in Linux using the way described in documentation and insert the obtained code into C# code of "Program.cs" file.


  8. Open terminal and compile the .NET project using the following command:
    dotnet build Scan_Images.csproj
    



    Close the terminal.

  9. Go to "bin/Debug/net7.0/" folder.


  10. Open the terminal and run the .NET application using the following command:
    dotnet ./Scan_Images.dll
    



    Close the terminal.

  11. Open the created multipage TIFF file and see the results: