Scan and Convert Files to TIFF in C#
This guide explains how to scan a physical document with a scanner and then save the scanned image as a TIFF file. This guide uses the TWAIN protocol.
Printing and scanning aren’t supported in the cross-platform .NET 6.0 assembly. For more information, see the system compatibility guide.
To get an image from a scanner and then save it as a TIFF file, follow these steps:
-
Create a
GdPictureImaging
object. -
Store the handle of the active windows in a variable by calling the
IntPtr.Zero
structure. -
Select the scanner by passing the handle to the
TwainSelectSource
and theTwainOpenDefaultSource
methods of theGdPictureImaging
object. -
Optional: Hide the scanning user interface with the
TwainSetHideUI
method of theGdPictureImaging
object. Use this setting when your application cannot communicate with the scanner. -
Get the image from the scanner by passing the handle to the
TwainAcquireToGdPictureImage
method of theGdPictureImaging
object. -
Save the scanned image with the
SaveAsTIFF
method of theGdPictureImaging
object. This method takes the following parameters:-
The image ID.
-
The file path of the output file.
-
The TIFF compression method. This parameter is a member of the
TiffCompression
enumeration.
-
-
Release unnecessary resources and close the TWAIN source handle.
The example below gets an image from a scanner and then saves it as a TIFF file:
using GdPictureImaging gdpictureImaging = new GdPictureImaging(); // Store the handle of the active windows in a variable. IntPtr WINDOW_HANDLE = IntPtr.Zero; // Select the scanner. gdpictureImaging.TwainSelectSource(WINDOW_HANDLE); gdpictureImaging.TwainOpenDefaultSource(WINDOW_HANDLE); // (Optional) Hide the scanning user interface. gdpictureImaging.TwainSetHideUI(true); // Get the image from the scanner. int imageId = gdpictureImaging.TwainAcquireToGdPictureImage(WINDOW_HANDLE); // Save the scanned image. gdpictureImaging.SaveAsTIFF(imageId, @"C:\temp\output.tiff", TiffCompression.TiffCompressionAUTO); // Release unnecessary resources. gdpictureImaging.ReleaseGdPictureImage(imageId); gdpictureImaging.TwainCloseSource();
Using gdpictureImaging As GdPictureImaging = New GdPictureImaging() ' Store the handle of the active windows in a variable. Dim WINDOW_HANDLE = IntPtr.Zero ' Select the scanner. gdpictureImaging.TwainSelectSource(WINDOW_HANDLE) gdpictureImaging.TwainOpenDefaultSource(WINDOW_HANDLE) ' (Optional) Hide the scanning user interface. gdpictureImaging.TwainSetHideUI(True) ' Get the image from the scanner. Dim imageId As Integer = gdpictureImaging.TwainAcquireToGdPictureImage(WINDOW_HANDLE) ' Save the scanned image. gdpictureImaging.SaveAsTIFF(imageId, "C:\temp\output.tiff", TiffCompression.TiffCompressionAUTO) ' Release unnecessary resources. gdpictureImaging.ReleaseGdPictureImage(imageId) gdpictureImaging.TwainCloseSource() End Using