Click here to Skip to main content
15,898,010 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.3M   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

 
AnswerRe: Configuring Scanning Resolution [modified] Pin
cmchuan13-Sep-06 18:01
cmchuan13-Sep-06 18:01 
QuestionRe: Configuring Scanning Resolution Pin
Victor VP7-Nov-06 21:23
Victor VP7-Nov-06 21:23 
GeneralScan once, but not twice Pin
Bastid27-Aug-06 11:20
Bastid27-Aug-06 11:20 
GeneralConfiguring scan area Pin
sbayeta22-Aug-06 12:00
sbayeta22-Aug-06 12:00 
GeneralRe: Configuring scan area Pin
cmchuan13-Sep-06 19:24
cmchuan13-Sep-06 19:24 
GeneralRe: Configuring scan area Pin
cmchuan18-Sep-06 16:23
cmchuan18-Sep-06 16:23 
QuestionRe: Configuring scan area Pin
yo ncv15-Oct-06 23:00
yo ncv15-Oct-06 23:00 
AnswerRe: Configuring scan area Pin
cmchuan29-Oct-06 22:42
cmchuan29-Oct-06 22:42 
Public Sub Acquire()
Dim rc As TwRC
CloseSrc()
If Equals(appid.Id, IntPtr.Zero) = True Then
Init(hwnd)
If Equals(appid.Id, IntPtr.Zero) = True Then
Return
End If
End If

rc = DSMident(appid, IntPtr.Zero, TwDG.Control, TwDAT.Identity, TwMSG.OpenDS, srcds)
If (rc <> TwRC.Success) Then
Return
End If

'Set Unit to Pixels
Dim Pixels As TwUnit = TwUnit.twPIXELS
Dim capUnit As TwCapability = New TwCapability(TwCap.IUnits, Pixels, TwType.Int16)
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, capUnit)
If rc <> TwRC.Success Then
CloseSrc()
Return
End If

Dim xcap As TwCapability = New TwCapability(TwCap.XScaling, XScale, TwType.Fix32)
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, xcap)
If rc <> TwRC.Success Then
CloseSrc()
Return
End If

xcap = New TwCapability(TwCap.YScaling, YScale, TwType.Fix32)
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, xcap)
If rc <> TwRC.Success Then
CloseSrc()
Return
End If


Dim ps As TwCapability = New TwCapability(TwCap.SupportedSizes, PaperSize, TwType.Int16)
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, ps)
If rc <> TwRC.Success Then
CloseSrc()
Return
End If

'Set Layout
Dim Layout As TwImageLayout = New TwImageLayout
rc = DSilayout(appid, srcds, TwDG.Image, TwDAT.ImageLayout, TwMSG.Get, Layout)
If rc <> TwRC.Success Then
CloseSrc()
Return
End If
If TopMargin > 0 Then
Layout.Frame.Top.FromFloat(CSng(TopMargin))
End If
If LeftMargin > 0 Then
Layout.Frame.Left.FromFloat(CSng(LeftMargin))
End If
If RightMargin > 0 Then
Layout.Frame.Right.FromFloat(CSng(RightMargin))
End If
If BottomMargin > 0 Then
Layout.Frame.Bottom.FromFloat(CSng(BottomMargin))
End If
Layout.FrameNumber = 1
Layout.PageNumber = 1
Layout.DocumentNumber = 1
rc = Me.DSilayout(appid, srcds, TwDG.Image, TwDAT.ImageLayout, TwMSG.Set, Layout)
If rc <> TwRC.Success Then
CloseSrc()
Return
End If

'Scan Colour
Dim Ccap As TwCapability = New TwCapability(TwCap.IPixelType, SColor, TwType.UInt16)
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, Ccap)
If (rc <> TwRC.Success) Then
CloseSrc()
Return
End If

Dim cap As TwCapability = New TwCapability(TwCap.XferCount, 1, TwType.Int16)
rc = DScap(appid, srcds, TwDG.Control, TwDAT.Capability, TwMSG.Set, cap)
If (rc <> TwRC.Success) Then
CloseSrc()
Return
End If

Dim guif As TwUserInterface = New TwUserInterface
guif.ShowUI = 1
guif.ModalUI = 1
guif.ParentHand = hwnd
rc = DSuserif(appid, srcds, TwDG.Control, TwDAT.UserInterface, TwMSG.EnableDS, guif)
If (rc <> TwRC.Success) Then
CloseSrc()
Return
End If

End Sub

'Full code here. Just replace the original Acquire in TwainLib.vb from NETMaster. It should be work.

'Remember to change this also in the TwainDefs.vb.

<StructLayout(LayoutKind.Sequential, Pack:=2, CharSet:=CharSet.Ansi)> Friend Class TwIdentity
Public Id As IntPtr
Public Version As TwVersion
Public ProtocolMajor As Short
Public ProtocolMinor As Short
Public SupportedGroups As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public Manufacturer As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public ProductFamily As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public ProductName As String
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2, CharSet:=CharSet.Ansi)> Friend Structure TwVersion
Public MajorNum As Short
Public MinorNum As Short
Public Language As Short
Public Country As Short
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=34)> Public Info As String
End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwUserInterface
Public ShowUI As Short
Public ModalUI As Short
Public ParentHand As IntPtr
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwStatus
Public ConditionCode As Short
Public Reserved As Short
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Structure TwEvent
Public EventPtr As IntPtr
Public Message As Short
End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwImageInfo
Public XResolution As Int32
Public YResolution As Int32
Public ImageWidth As Int32
Public ImageLength As Int32
Public SamplesPerPixel As Int16
<MarshalAs(UnmanagedType.ByValArray, SizeConst:=8)> Public BitsPerSample() As Short
Public BitsPerPixel As Int16
Public Planar As Boolean
Public PixelType As Int16
Public Compression As Short
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwPendingXfers
Public Count As Short
Public EOJ As Integer
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Structure TwFix32
Public Whole As System.Int16
Public Frac As System.UInt32

Public Function ToFloat() As Single
Dim frac_sng As Single
frac_sng = System.Convert.ToSingle(Frac)
Return CType(Whole + (CType(frac_sng, Single) / 65536.0F), Single)
End Function

Public Sub FromFloat(ByVal f As Single)
Dim i As Int32 = CType(((f * 65536.0F) + 0.5F), Int32)
Whole = System.Convert.ToInt16(i / 2 ^ 16)
Frac = System.Convert.ToUInt32((i Or &HFFFF))
End Sub

End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Structure TwFrame
Public Left As TwFix32
Public Top As TwFix32
Public Right As TwFix32
Public Bottom As TwFix32
End Structure

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwImageLayout
Public Frame As TwFrame
Public DocumentNumber As Integer
Public PageNumber As Integer
Public FrameNumber As Integer
End Class

<StructLayout(LayoutKind.Sequential, Pack:=2)> Friend Class TwCapability
Public Cap As Short
Public ConType As Short
Public Handle As IntPtr
Public Sub TwCapability(ByVal capIn As TwCap)
Cap = CType(capIn, Short)
ConType = -1
End Sub

Public Sub New(ByVal capIn As TwCap, ByVal sval As Short, ByVal TWType As TwType)
Cap = CType(capIn, Short)
ConType = CType(TwOn.One, Short)
Handle = Twain.GlobalAlloc(&H42, 6)
Dim pv As IntPtr = Twain.GlobalLock(Handle)
Marshal.WriteInt16(pv, 0, CType(TWType, Short))
Marshal.WriteInt32(pv, 2, CType(sval, Short))
Twain.GlobalUnlock(Handle)
End Sub

Public Sub Dispose()
If Not Equals(Handle, IntPtr.Zero) Then
Twain.GlobalFree(Handle)
End If
End Sub

Protected Overrides Sub Finalize()
If Not Equals(Handle, IntPtr.Zero) Then
Twain.GlobalFree(Handle)
End If
End Sub
End Class


Generalmultiple interface with multiple classes Pin
joseph palatti13-Aug-06 21:43
joseph palatti13-Aug-06 21:43 
GeneralHelp, please. it doesn't work in the child window, I mean i add this to a child window, and it nothing happen. Pin
zhuangliang.zheng6-Aug-06 21:38
zhuangliang.zheng6-Aug-06 21:38 
GeneralRe: Help, please. it doesn't work in the child window, I mean i add this to a child window, and it nothing happen. Pin
izzetfatih@yahoo.com23-Nov-06 4:19
izzetfatih@yahoo.com23-Nov-06 4:19 
GeneralNot Working on VS 2005,,, Pin
Ziad Khoury1-Aug-06 7:30
Ziad Khoury1-Aug-06 7:30 
GeneralRe: Not Working on VS 2005,,, Pin
Ziad Khoury1-Aug-06 7:38
Ziad Khoury1-Aug-06 7:38 
QuestionSelect Source command and Nothing happens Pin
huseyin26-Jul-06 10:23
huseyin26-Jul-06 10:23 
QuestionUnable to do multipage scanning Pin
asp-12321-Jul-06 5:49
asp-12321-Jul-06 5:49 
AnswerRe: Unable to do multipage scanning Pin
trimba20-Aug-06 21:07
trimba20-Aug-06 21:07 
GeneralRe: Unable to do multipage scanning Pin
Emanuele Zambrano20-Aug-06 23:13
Emanuele Zambrano20-Aug-06 23:13 
GeneralRe: Unable to do multipage scanning Pin
alanmac13-Feb-07 14:22
alanmac13-Feb-07 14:22 
QuestionRe: Unable to do multipage scanning Pin
Jwalant Natvarlal Soneji29-Jun-07 1:45
Jwalant Natvarlal Soneji29-Jun-07 1:45 
AnswerRe: Unable to do multipage scanning Pin
Irv Adams11-Aug-09 9:57
Irv Adams11-Aug-09 9:57 
AnswerRe: Unable to do multipage scanning Pin
ymamalis2-Dec-09 3:35
ymamalis2-Dec-09 3:35 
GeneralCorrection for overflow checking on Pin
tobias00421-Jul-06 4:17
tobias00421-Jul-06 4:17 
QuestionHow Custominze Scan Area?? Pin
muhsyed010-Jul-06 1:21
muhsyed010-Jul-06 1:21 
AnswerRe: How Custominze Scan Area?? Pin
gabegabe13-Jul-06 20:27
gabegabe13-Jul-06 20:27 
AnswerRe: How Custominze Scan Area?? Pin
muhsyed019-Jul-06 4:28
muhsyed019-Jul-06 4:28 

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.