Click here to Skip to main content
15,887,746 members
Articles / Programming Languages / C#
Article

.NET TWAIN image scanner

Rate me:
Please Sign up or sign in to vote.
4.91/5 (227 votes)
12 May 2002Public Domain2 min read 7.2M   132.2K   421   996
Using TWAIN API to scan images

Sample Screenshot

Abstract

In Windows imaging applications, the most used API for scanning is TWAIN www.twain.org. Unfortunately, the new .NET Framework has no built-in support for TWAIN. So we have to work with the interop methods of .NET to access this API. This article doesn't explain this interop techniques, and good knowledge of the TWAIN 1.9 specifications is assumed! The sample code included doesn't present a finished library, only some essential steps for a minimal TWAIN adaption to .NET applications.

Details

First step was to port the most important parts of TWAIN.H, these are found in TwainDefs.cs. The real logic for calling TWAIN is coded in the class Twain, in file TwainLib.cs.. As the TWAIN API is exposed by the Windows DLL, twain_32.dll, we have to use the .NET DllImport mechanism for interop with legacy code. This DLL has the central DSM_Entry(), ordinal #1 function exported as the entry point to TWAIN. This call has numerous parameters, and the last one is of variable type! It was found to be best if we declare multiple variants of the call like:

C#
[DllImport("twain_32.dll", EntryPoint="#1")]
private static extern TwRC DSMparent(
    [In, Out] TwIdentity origin,
    IntPtr zeroptr,
    TwDG dg, TwDAT dat, TwMSG msg,
    ref IntPtr refptr );

The Twain class has a simple 5-step interface:

C#
class Twain
{
    Init();
    Select();
    Acquire();
    PassMessage();
    TransferPictures();
}

For some sort of 'callbacks', TWAIN uses special Windows messages, and these must be caught from the application-message-loop. In .NET, the only way found was IMessageFilter.PreFilterMessage(), and this filter has to be activated with a call like Application.AddMessageFilter(). Within the filter method, we have to forward each message to Twain.PassMessage(), and we get a hint (enum TwainCommand) back for how we have to react.

Sample App

The sample is a Windows Forms MDI-style application. It has the two TWAIN-related menu items Select Source... and Acquire... Once an image is scanned in, we can save it to a file in any of the GDI+ supported file formats (BMP, GIF, TIFF, JPEG...)

Limitations

All code was only tested on Windows 2000SP2, with an Epson Perfection USB scanner and an Olympus digital photo camera. The scanned picture is (by TWAIN spec) a Windows DIB, and the sample code has VERY little checking against error return codes and bitmap formats. Unfortunately, no direct method is available in .NET to convert a DIB to the managed Bitmap class... Some known problems may show up with color palettes and menus.

Note, TWAIN has it's root in 16-Bit Windows! For a more modern API supported on Windows ME/XP, have a look at Windows Image Acquisition (WIA).

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Web Developer
Switzerland Switzerland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionnewbie question: mdi child form problem. Pin
dude25175418-Oct-09 18:49
dude25175418-Oct-09 18:49 
QuestionConnect to network scanner Pin
ihsan4u28-Sep-09 0:17
ihsan4u28-Sep-09 0:17 
AnswerRe: Connect to network scanner Pin
James West1-Nov-09 12:08
James West1-Nov-09 12:08 
AnswerEpson Supported Twain Commands Pin
JohnSims19421-Sep-09 1:07
JohnSims19421-Sep-09 1:07 
AnswerScanner with Document Feeder PinPopular
JohnSims19421-Sep-09 1:05
JohnSims19421-Sep-09 1:05 
GeneralRe: Scanner with Document Feeder Pin
Member 39132834-Nov-09 23:23
Member 39132834-Nov-09 23:23 
GeneralRe: Scanner with Document Feeder Pin
Member 39132834-Nov-09 23:35
Member 39132834-Nov-09 23:35 
AnswerRe: Scanner with Document Feeder Pin
JohnSims1944-Nov-09 23:50
JohnSims1944-Nov-09 23:50 
Hmm - the code you've placed this above is in VB where as the code I gave is in C#. The code needs to be placed in TwainLib.cs under the "public void Aquire". To make it easy I've added the whole of my copy of the void below:

public void Acquire()
		{
		TwRC rc;
		CloseSrc();
		if( appid.Id == IntPtr.Zero )
			{
			Init( hwnd );
			if( appid.Id == IntPtr.Zero )
				return;
			}
		rc = DSMident( appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.OpenDS, srcds );
		if( rc != TwRC.Success )
			return;

        // 1 = only 1 image if we're not using the user interface
        // -1 = scan all images if we're not using the user interface
		TwCapability cap = new TwCapability( TwCap.XferCount, -1 );
		rc = DScap( appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, cap );
		if( rc != TwRC.Success )
			{
			CloseSrc();
			return;
			}

        // This bit sets it to use duplex scanning
        // Had to overload the TwCapability method for this and add the enum of CAP_DUPLEXENABLED
        // The enums can be found at http://guides.gdpicture.com/v6/html/content/frames.html?frmname=topic&frmfile=TwainCapabilities.html
        TwCapability capDuplex = new TwCapability(TwCap.CAP_DUPLEXENABLED, 0, TwType.Bool);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capDuplex);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        // Set the X resolution
        TwCapability capResX = new TwCapability(TwCap.CAP_RESX, 150, TwType.Fix32);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capResX);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        // Set the Y resolution
        TwCapability capResY = new TwCapability(TwCap.CAP_RESY, 150, TwType.Fix32);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capResY);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        // Set the scan type
        // 0 = BW | 1 = Gray | 4 = Colour
        TwCapability capPixelType = new TwCapability(TwCap.IPixelType, 0);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capPixelType);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        // Set the scan size to A4
        TwCapability capPaperSize = new TwCapability(TwCap.ICAP_SUPPORTEDSIZES, 1);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capPaperSize);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        //// Set the automatic deskew
        TwCapability capAutoDeskew = new TwCapability(TwCap.ICAP_AUTOMATICDESKEW, 1, TwType.Bool);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capAutoDeskew);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        //// Set the autoscan pre catch
        TwCapability capAutoScan = new TwCapability(TwCap.CAP_AUTOSCAN, 1, TwType.Bool);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capAutoScan);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        //// Set the threshold (bw only)
        TwCapability capThreshold = new TwCapability(TwCap.ICAP_THRESHOLD, 100, TwType.Fix32 );
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capThreshold);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        //// Set the brightness (doesn't work for BW)
        TwCapability capBrightness = new TwCapability(TwCap.ICAP_BRIGHTNESS, 400, TwType.Fix32);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capBrightness);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        //// Set the gamma (doesn't work for BW)
        TwCapability capGamma = new TwCapability(TwCap.ICAP_GAMMA, 2, TwType.Fix32);
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capGamma);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }

        //// Set the halftones !need to look at the capability overload
        TwCapability capHalfTones = new TwCapability(TwCap.ICAP_HALFTONES, "TextEnhancement Technology");
        rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capHalfTones);
        if (rc != TwRC.Success)
        {
            CloseSrc();
            return;
        }


        TwUserInterface	guif = new TwUserInterface();
        // ShowUI = 0 hide the user interface | 1 shows the user interface
		guif.ShowUI = 0;
		guif.ModalUI = 1;
		guif.ParentHand = hwnd;
		rc = DSuserif( appid, srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.EnableDS, guif );
		if( rc != TwRC.Success )
			{
			CloseSrc();
			return;
			}
		}


You then need to update the TwainDef.cs file and replace the "internal enum TwCap : short" with the following (the bits commented // DOESN'T WORK are just commands that my particular scanner wouldn't support):

internal enum TwCap : short
	{
	XferCount		= 0x0001,			// CAP_XFERCOUNT
	ICompression	= 0x0100,			// ICAP_...
	IPixelType		= 0x0101,
	IUnits			= 0x0102,
	IXferMech		= 0x0103,
    CAP_DUPLEXENABLED = 0x1013,
    CAP_RESX = 0x1118,
    CAP_RESY = 0x1119,
    ICAP_SUPPORTEDSIZES = 0x1122,
    ICAP_AUTOMATICDESKEW = 0x1151,
    ICAP_AUTOMATICROTATE = 0x1152,      // DOESN'T WORK
    ICAP_AUTODISCARDBLANKPAGES = 0x1134,// DOESN'T WORK
    ICAP_NOISEFILTER = 0x1148, //DOESN'T WORK
    ICAP_AUTOBRIGHT = 0x1100, //DOESN'T WORK
    CAP_AUTOSCAN = 0x1010,
    ICAP_THRESHOLD = 0x1123,
    ICAP_BRIGHTNESS = 0x1101,
    ICAP_GAMMA = 0x1108,
    ICAP_HALFTONES = 0x1109,
    ICAP_PIXELFLAVOR = 0x111F //DOESN'T WORK
	}


Then also in the TwainDef.cs near the bottom you'll find this:

public TwCapability(TwCap cap, string sval)
    {
        Cap = (short)cap;
        ConType = (short)TwOn.One;
        Handle = Twain.GlobalAlloc(0x42, 6);
        IntPtr pv = Twain.GlobalLock(Handle);
        Marshal.WriteInt16(pv, 0, (short)TwType.Str32);
        Marshal.StringToHGlobalUni(sval);
        Twain.GlobalUnlock(Handle);
    }


Underneath this stick the following code in:

public TwCapability(TwCap cap, short sval, TwType TheType)
    {
        Cap = (short)cap;
        ConType = (short)TwOn.One;
        Handle = Twain.GlobalAlloc(0x42, 6);
        IntPtr pv = Twain.GlobalLock(Handle);
        if (TheType == TwType.Bool)
        {
            Marshal.WriteInt16(pv, 0, (short)TwType.Bool);
        }
        if (TheType == TwType.Fix32)
        {
            Marshal.WriteInt16(pv, 0, (short)TwType.Fix32);
        }
        
        Marshal.WriteInt32(pv, 2, (int)sval);
        Twain.GlobalUnlock(Handle);
    }

It should all work then
GeneralRe: Scanner with Document Feeder Pin
zlov29-Sep-10 0:17
zlov29-Sep-10 0:17 
QuestionPassing a string to TwCapability Pin
JohnSims19421-Sep-09 0:46
JohnSims19421-Sep-09 0:46 
GeneralDSuserif will cause exception AccessViolationException: Pin
carlshe19-Sep-09 20:17
carlshe19-Sep-09 20:17 
GeneralRe: DSuserif will cause exception AccessViolationException: Pin
LupinTheThird30-Oct-11 10:50
LupinTheThird30-Oct-11 10:50 
QuestionHow to implement it to the User Control Pin
chandresh.softobiz16-Sep-09 17:50
chandresh.softobiz16-Sep-09 17:50 
GeneralIs it possible to scan just one document from feeder Pin
zodiacseven11-Aug-09 3:20
zodiacseven11-Aug-09 3:20 
GeneralUse Duplex with Driver Twain - Help URGENT Pin
IvesBertoli30-Jul-09 2:44
IvesBertoli30-Jul-09 2:44 
GeneralRe: Use Duplex with Driver Twain - Help URGENT Pin
JohnSims19418-Sep-09 0:47
JohnSims19418-Sep-09 0:47 
GeneralRe: Use Duplex with Driver Twain - Help URGENT Pin
bennyshani19-Oct-09 11:38
bennyshani19-Oct-09 11:38 
GeneralRe: Use Duplex with Driver Twain -Going Insane Pin
morke4-Jan-10 1:23
morke4-Jan-10 1:23 
GeneralRe: Use Duplex with Driver Twain -Going Insane Pin
bennyshani4-Jan-10 3:19
bennyshani4-Jan-10 3:19 
GeneralRe: Use Duplex with Driver Twain -Going Insane Pin
morke4-Jan-10 23:02
morke4-Jan-10 23:02 
Generalrunning to dead when cancel Pin
pclion17-Jun-09 18:04
pclion17-Jun-09 18:04 
AnswerRe: running to dead when cancel Pin
Wolexie21-Jun-09 2:01
Wolexie21-Jun-09 2:01 
Generalchange the source of the image to be acquire Pin
AlexG Solutions9-Jun-09 11:09
AlexG Solutions9-Jun-09 11:09 
GeneralRe: change the source of the image to be acquire Pin
Vankir24-Nov-09 7:07
Vankir24-Nov-09 7:07 
General1bpp b/w DIB problem Pin
nasharu17-Apr-09 8:27
nasharu17-Apr-09 8:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.