Click here to Skip to main content
15,890,399 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

 
QuestionTutorial? Pin
Diagon Alley8-Dec-05 18:45
Diagon Alley8-Dec-05 18:45 
AnswerRe: Tutorial? Pin
jgoemat10-Mar-06 15:51
jgoemat10-Mar-06 15:51 
GeneralRe: Tutorial? Pin
Diagon Alley14-Mar-06 7:39
Diagon Alley14-Mar-06 7:39 
Question1-bit scanning Pin
AlexKak8-Dec-05 2:17
AlexKak8-Dec-05 2:17 
GeneralGreat Job Pin
Santiago Corredoira5-Nov-05 3:47
Santiago Corredoira5-Nov-05 3:47 
GeneralAuto Crop to be set Programatically Pin
Nil_Gup4-Nov-05 2:19
Nil_Gup4-Nov-05 2:19 
GeneralCompressing the image Pin
jptros13-Oct-05 11:44
jptros13-Oct-05 11:44 
AnswerRe: Compressing the image Pin
olm_23@yahoo.com1-Dec-05 11:10
olm_23@yahoo.com1-Dec-05 11:10 
hi, I found this code and I send you as is, RESPECTING THE AUTHOR'S RIGHT, I'M JUST LEARNING.

I've changed a small part of code. instead of use this:

///////////////////////////////////////////////////////////////////////////////////77
byte[] data = new byte[ fh.Size ]; // file-sized byte[]
RawSerializeInto( fh, data ); // serialize BITMAPFILEHEADER into byte[]
Marshal.Copy( dibPtr, data, fhSize, dibSize ); // mem-copy DIB into byte[]
MemoryStream stream = new MemoryStream( data ); // file-sized stream
Bitmap tmp = new Bitmap( stream ); // 'tmp' is wired to stream (unfortunately)

Bitmap result = new Bitmap( tmp ); // THIS IS THE LINE I'VE HAD CHANGED
tmp.Dispose(); tmp = null;
stream.Close(); stream = null; data = null;
return result;

///////////////////////////////////////////////////////////////////////////////////////////


I'VE USED THIS:

////////////////////////////////////////////////////////////////
tmp.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg);
Bitmap result = new Bitmap( tmp ); // 'result' is a copy (stand-alone)
result.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg);

////////////////////////////////////////////////////////////////



AN THIS IS THE WHOLE CODE

// *******************************************************************************************
/* **************************************************************************
Converting memory DIB to .NET 'Bitmap' object
EXPERIMENTAL, USE AT YOUR OWN RISK
http://dnetmaster.net/
*****************************************************************************/
//
// The 'DibToImage' class provides three different methods [Stream/scan0/HBITMAP alive]
//
// The parameter 'IntPtr dibPtr' is a pointer to
// a classic GDI 'packed DIB bitmap', starting with a BITMAPINFOHEADER
//
// Note, all this methods will use MUCH memory!
// (multiple copies of pixel datas)
//
// Whatever I used, all Bitmap/Image constructors
// return objects still beeing backed by the underlying Stream/scan0/HBITMAP.
// Thus you would have to keep the Stream/scan0/HBITMAP alive!
//
// So I tried to make an exact copy/clone of the Bitmap:
// But e.g. Bitmap.Clone() doesn't make a stand-alone duplicate.
// The working method I used here is : Bitmap copy = new Bitmap( original );
// Unfortunately, the returned Bitmap will always have a pixel-depth of 32bppARGB !
// But this is a pure GDI+/.NET problem... maybe somebody else can help?
//
//
// ----------------------------
// Note, Microsoft should really wrap GDI+ 'GdipCreateBitmapFromGdiDib' in .NET!
// This would be very useful!
//
// There is a :
// Bitmap Image.FromHbitmap( IntPtr hbitmap )
// so there is NO reason to not add a:
// Bitmap Image.FromGdiDib( IntPtr dibptr )
//
// PLEASE SEND EMAIL TO: netfwsdk@microsoft.com
// OR mswish@microsoft.com
// OR http://register.microsoft.com/mswish/suggestion.asp
// ------------------------------------------------------------------------

using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;


namespace TwainGui
{

public class DibToImage
{


///
/// Get .NET 'Bitmap' object from memory DIB via stream constructor.
/// This should work for most DIBs.
///

/// <param name="dibPtr" />Pointer to memory DIB, starting with BITMAPINFOHEADER.
public static Bitmap WithStream( IntPtr dibPtr )
{
BITMAPFILEHEADER fh = new BITMAPFILEHEADER();
Type bmiTyp = typeof(BITMAPINFOHEADER);
BITMAPINFOHEADER bmi = (BITMAPINFOHEADER) Marshal.PtrToStructure( dibPtr, bmiTyp );
if( bmi.biSizeImage == 0 )
bmi.biSizeImage = ((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * Math.Abs( bmi.biHeight );
if( (bmi.biClrUsed == 0) && (bmi.biBitCount < 16) )
bmi.biClrUsed = 1 << bmi.biBitCount;

int fhSize = Marshal.SizeOf( typeof(BITMAPFILEHEADER) );
int dibSize = bmi.biSize + (bmi.biClrUsed * 4) + bmi.biSizeImage; // info + rgb + pixels

fh.Type = new Char[] { 'B', 'M' }; // "BM"
fh.Size = fhSize + dibSize; // final file size
fh.OffBits = fhSize + bmi.biSize + (bmi.biClrUsed * 4); // offset to pixels

byte[] data = new byte[ fh.Size ]; // file-sized byte[]
RawSerializeInto( fh, data ); // serialize BITMAPFILEHEADER into byte[]
Marshal.Copy( dibPtr, data, fhSize, dibSize ); // mem-copy DIB into byte[]

MemoryStream stream = new MemoryStream( data ); // file-sized stream
Bitmap tmp = new Bitmap( stream ); // 'tmp' is wired to stream (unfortunately)

tmp.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg);
Bitmap result = new Bitmap( tmp ); // 'result' is a copy (stand-alone)
result.Save(stream,System.Drawing.Imaging.ImageFormat.Jpeg);

tmp.Dispose(); tmp = null;
stream.Close(); stream = null; data = null;
return result;
}



///
/// Get .NET 'Bitmap' object from memory DIB via 'scan0' constructor.
/// This only works for 16..32 pixel-depth RGB DIBs (no color palette)!
///

/// <param name="dibPtr" />Pointer to memory DIB, starting with BITMAPINFOHEADER.
public static Bitmap WithScan0( IntPtr dibPtr )
{
Type bmiTyp = typeof(BITMAPINFOHEADER);
BITMAPINFOHEADER bmi = (BITMAPINFOHEADER) Marshal.PtrToStructure( dibPtr, bmiTyp );
if( bmi.biCompression != 0 )
throw new ArgumentException( "Invalid bitmap format (non-RGB)", "BITMAPINFOHEADER.biCompression" );

PixelFormat fmt = PixelFormat.Undefined;
if( bmi.biBitCount == 24 )
fmt = PixelFormat.Format24bppRgb;
else if( bmi.biBitCount == 32 )
fmt = PixelFormat.Format32bppRgb;
else if( bmi.biBitCount == 16 )
fmt = PixelFormat.Format16bppRgb555;
else // we don't support a color palette...
throw new ArgumentException( "Invalid pixel depth (<16-Bits)", "BITMAPINFOHEADER.biBitCount" );

int scan0 = ((int) dibPtr) + bmi.biSize + (bmi.biClrUsed * 4); // pointer to pixels
int stride = (((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3; // bytes/line
if( bmi.biHeight > 0 )
{ // bottom-up
scan0 += stride * (bmi.biHeight - 1);
stride = -stride;
}
Bitmap tmp = new Bitmap( bmi.biWidth, Math.Abs( bmi.biHeight ),
stride, fmt, (IntPtr) scan0 ); // 'tmp' is wired to scan0 (unfortunately)
Bitmap result = new Bitmap( tmp ); // 'result' is a copy (stand-alone)
tmp.Dispose(); tmp = null;
return result;
}





///
/// Get .NET 'Bitmap' object from memory DIB via HBITMAP.
/// Uses many temporary copies [huge memory usage]!
///

/// <param name="dibPtr" />Pointer to memory DIB, starting with BITMAPINFOHEADER.
public static Bitmap WithHBitmap( IntPtr dibPtr )
{
Type bmiTyp = typeof(BITMAPINFOHEADER);
BITMAPINFOHEADER bmi = (BITMAPINFOHEADER) Marshal.PtrToStructure( dibPtr, bmiTyp );
if( bmi.biSizeImage == 0 )
bmi.biSizeImage = ((((bmi.biWidth * bmi.biBitCount) + 31) & ~31) >> 3) * Math.Abs( bmi.biHeight );
if( (bmi.biClrUsed == 0) && (bmi.biBitCount < 16) )
bmi.biClrUsed = 1 << bmi.biBitCount;

IntPtr pixPtr = new IntPtr( (int) dibPtr + bmi.biSize + (bmi.biClrUsed * 4) ); // pointer to pixels

IntPtr img = IntPtr.Zero;
int st = GdipCreateBitmapFromGdiDib( dibPtr, pixPtr, ref img );
if( (st != 0) || (img == IntPtr.Zero) )
throw new ArgumentException( "Invalid bitmap for GDI+", "IntPtr dibPtr" );

IntPtr hbitmap;
st = GdipCreateHBITMAPFromBitmap( img, out hbitmap, 0 );
if( (st != 0) || (hbitmap == IntPtr.Zero) )
{
GdipDisposeImage( img );
throw new ArgumentException( "can't get HBITMAP with GDI+", "IntPtr dibPtr" );
}

Bitmap tmp = Image.FromHbitmap( hbitmap ); // 'tmp' is wired to hbitmap (unfortunately)
Bitmap result = new Bitmap( tmp ); // 'result' is a copy (stand-alone)
tmp.Dispose(); tmp = null;
bool ok = DeleteObject( hbitmap ); hbitmap = IntPtr.Zero;
st = GdipDisposeImage( img ); img = IntPtr.Zero;
return result;
}



/// Copy structure into Byte-Array.
private static void RawSerializeInto( object anything, byte[] datas )
{
int rawsize = Marshal.SizeOf( anything );
if( rawsize > datas.Length )
throw new ArgumentException( " buffer too small ", " byte[] datas " );
GCHandle handle = GCHandle.Alloc( datas, GCHandleType.Pinned );
IntPtr buffer = handle.AddrOfPinnedObject();
Marshal.StructureToPtr( anything, buffer, false );
handle.Free();
}



// GDI imports : read MSDN!

[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi, Pack=1)]
private class BITMAPFILEHEADER
{
[MarshalAs( UnmanagedType.ByValArray, SizeConst=2)]
public Char[] Type;
public Int32 Size;
public Int16 reserved1;
public Int16 reserved2;
public Int32 OffBits;
}

[StructLayout(LayoutKind.Sequential, Pack=2)]
private class BITMAPINFOHEADER
{
public int biSize;
public int biWidth;
public int biHeight;
public short biPlanes;
public short biBitCount;
public int biCompression;
public int biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public int biClrUsed;
public int biClrImportant;
}

[DllImport("gdi32.dll", ExactSpelling=true)]
private static extern bool DeleteObject( IntPtr obj );



// GDI+ from GdiplusFlat.h : http://msdn.microsoft.com/library/en-us/gdicpp/gdi+/gdi+reference/flatapi.asp

[DllImport("gdiplus.dll", ExactSpelling=true)]
private static extern int GdipCreateBitmapFromGdiDib( IntPtr bminfo, IntPtr pixdat, ref IntPtr image );
// GpStatus WINGDIPAPI GdipCreateBitmapFromGdiDib( GDIPCONST BITMAPINFO* gdiBitmapInfo, VOID* gdiBitmapData, GpBitmap** bitmap);

[DllImport("gdiplus.dll", ExactSpelling=true)]
private static extern int GdipCreateHBITMAPFromBitmap( IntPtr image, out IntPtr hbitmap, int bkg );
// GpStatus WINGDIPAPI GdipCreateHBITMAPFromBitmap( GpBitmap* bitmap, HBITMAP* hbmReturn, ARGB background);

[DllImport("gdiplus.dll", ExactSpelling=true)]
private static extern int GdipDisposeImage( IntPtr image );

} // class DibToImage

} // namespace

// *******************************************************************************************
GeneralRe: Compressing the image Pin
Raja Chandrasekaran20-Feb-06 4:44
Raja Chandrasekaran20-Feb-06 4:44 
QuestionError when not selecting a source Pin
Diogo Alves15-Sep-05 3:26
Diogo Alves15-Sep-05 3:26 
AnswerRe: Error when not selecting a source Pin
Diogo Alves16-Sep-05 1:36
Diogo Alves16-Sep-05 1:36 
GeneralRe: Error when not selecting a source Pin
AhmadHamid19-Oct-05 21:32
AhmadHamid19-Oct-05 21:32 
GeneralRe: Error when not selecting a source Pin
sujanakar13-Dec-05 19:42
sujanakar13-Dec-05 19:42 
QuestionIs it possible to scan directly? Pin
ecmpain13-Sep-05 11:33
ecmpain13-Sep-05 11:33 
AnswerRe: Is it possible to scan directly? Pin
Triano19-Oct-05 3:18
Triano19-Oct-05 3:18 
AnswerRe: Is it possible to scan directly? Pin
Triano19-Oct-05 21:07
Triano19-Oct-05 21:07 
GeneralRe: Is it possible to scan directly? Pin
Gavrix15-Dec-05 4:30
Gavrix15-Dec-05 4:30 
QuestionRe: Is it possible to scan directly? Pin
Jwalant Natvarlal Soneji29-Jun-07 5:27
Jwalant Natvarlal Soneji29-Jun-07 5:27 
GeneralCancel Scan Pin
SuriouslyFoReal8-Sep-05 3:00
SuriouslyFoReal8-Sep-05 3:00 
GeneralRe: Cancel Scan Pin
AhmadHamid11-Nov-05 1:19
AhmadHamid11-Nov-05 1:19 
GeneralRe: Cancel Scan Pin
AhmadHamid11-Nov-05 8:33
AhmadHamid11-Nov-05 8:33 
GeneralDistinction between scanners and webcams Pin
Olivier DALET6-Sep-05 6:02
Olivier DALET6-Sep-05 6:02 
GeneralImage Acquisition Pin
sabster8-Aug-05 21:06
sabster8-Aug-05 21:06 
GeneralICAP_ImageLayout Pin
Dev_Calz5-Aug-05 7:35
Dev_Calz5-Aug-05 7:35 
GeneralRe: ICAP_ImageLayout Pin
Michael Lam21-Dec-05 22:41
Michael Lam21-Dec-05 22:41 

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.