Click here to Skip to main content
15,881,248 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.1M   132.1K   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

 
GeneralConverting this to a dll Pin
gthompson20052-May-04 17:39
gthompson20052-May-04 17:39 
GeneralRe: Converting this to a dll Pin
Anonymous7-May-04 12:59
Anonymous7-May-04 12:59 
GeneralRe: Converting this to a dll Pin
80x8623-May-04 9:02
80x8623-May-04 9:02 
Questionhow to get the scanned image into a picturebox? Pin
HansHunger26-Apr-04 4:24
HansHunger26-Apr-04 4:24 
AnswerRe: how to get the scanned image into a picturebox? Pin
William Ten Broek8-May-04 13:06
William Ten Broek8-May-04 13:06 
GeneralRe: how to get the scanned image into a picturebox? Pin
System.ZaX11-Jun-04 6:23
System.ZaX11-Jun-04 6:23 
GeneralRe: how to get the scanned image into a picturebox? Pin
11-Jun-04 23:56
suss11-Jun-04 23:56 
GeneralRe: how to get the scanned image into a picturebox? Pin
27-Jun-04 23:26
suss27-Jun-04 23:26 
I had left out the following code i do apologize for this

The Amature

using System.Drawing.Imaging ;

private ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
private bool GetCodecClsid( string filename, out Guid clsid )
{
clsid = Guid.Empty;
string ext = Path.GetExtension( filename );
if( ext == null )
return false;
ext = "*" + ext.ToUpper();
foreach( ImageCodecInfo codec in codecs )
{
if( codec.FilenameExtension.IndexOf( ext ) >= 0 )
{
clsid = codec.Clsid;
return true;
}
}
return false;
}

protected IntPtr GetPixelInfo( IntPtr bmpptr )
{
bmi = new BITMAPINFOHEADER();
Marshal.PtrToStructure( bmpptr, bmi );

bmprect.X = bmprect.Y = 0;
bmprect.Width = bmi.biWidth;
bmprect.Height = bmi.biHeight;

if( bmi.biSizeImage == 0 )
bmi.biSizeImage = ((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * bmi.biHeight;

int p = bmi.biClrUsed;
if( (p == 0) && (bmi.biBitCount <= 8) )
p = 1 << bmi.biBitCount;
p = (p * 4) + bmi.biSize + (int) bmpptr;
return (IntPtr) p;
}

[StructLayout(LayoutKind.Sequential, Pack=2)]
internal class BITMAPINFOHEADER
{
public int biSize = 0;
public int biWidth = 0;
public int biHeight = 0;
public short biPlanes = 0;
public short biBitCount = 0;
public int biCompression = 0;
public int biSizeImage = 0;
public int biXPelsPerMeter = 0;
public int biYPelsPerMeter = 0;
public int biClrUsed = 0;
public int biClrImportant = 0;
}
AnswerRe: how to get the scanned image into a picturebox? Pin
RBRChicho22-Nov-04 9:46
RBRChicho22-Nov-04 9:46 
Generaldistinguish any kind of scanners Pin
Member 102589321-Apr-04 19:39
Member 102589321-Apr-04 19:39 
Generalhelp in knoeing the scanner Pin
Member 102589316-Apr-04 7:22
Member 102589316-Apr-04 7:22 
GeneralRe: help in knoeing the scanner Pin
Anonymous16-Apr-04 20:43
Anonymous16-Apr-04 20:43 
GeneralCapture image frm webcam Pin
shahzad arfan10-Apr-04 6:16
sussshahzad arfan10-Apr-04 6:16 
GeneralRe: Capture image frm webcam Pin
Mr.Naveed10-Apr-04 8:51
Mr.Naveed10-Apr-04 8:51 
GeneralRe: Capture image frm webcam Pin
Anonymous14-Apr-04 3:38
Anonymous14-Apr-04 3:38 
GeneralRe: Capture image frm webcam Pin
Member 373470329-Dec-09 22:06
Member 373470329-Dec-09 22:06 
GeneralJPEG Quality Pin
mcfisto19-Mar-04 0:14
mcfisto19-Mar-04 0:14 
GeneralSetting Resolution Pin
bill davidheiser1-Mar-04 11:37
bill davidheiser1-Mar-04 11:37 
GeneralRe: Setting values Pin
ElGuroProgramador23-Mar-04 8:18
ElGuroProgramador23-Mar-04 8:18 
GeneralGet TwCap Properties Pin
ElGuroProgramador23-Feb-04 20:05
ElGuroProgramador23-Feb-04 20:05 
GeneralRe: Get TwCap Properties Pin
Steve Clarke7-May-04 10:49
Steve Clarke7-May-04 10:49 
GeneralRe: Get TwCap Properties Pin
Ming_Z10-Jul-06 10:34
Ming_Z10-Jul-06 10:34 
GeneralTO VB .NET Pin
Anonymous23-Feb-04 0:36
Anonymous23-Feb-04 0:36 
GeneralRe: TO VB .NET Pin
abohmann8-May-04 23:41
abohmann8-May-04 23:41 
GeneralUse of component with hp scanners Pin
alexAreaIT15-Feb-04 22:29
alexAreaIT15-Feb-04 22:29 

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.