Click here to Skip to main content
15,881,139 members
Articles / Desktop Programming / WPF

Twain for WPF Applications - Look Ma, No Handles

Rate me:
Please Sign up or sign in to vote.
4.94/5 (30 votes)
22 Mar 2011CPOL5 min read 139.1K   9.1K   81   58
A managed interface allows simple usage of Twain in WPF applications. Demo project provides scanning from cameras and scanners, display of multiple images and upload to a server via web services.

Introduction

This project provides a clean interface that enables using Twain in WPF projects.

The code includes two parts:

  1. A Twain abstraction layer 
  2. A demo application

The abstraction layer exposes a clean C# interface (no handles, IntPtrs, etc.). It contains a few CS files which deal with the necessary interfaces and activation of Twain.

The application demonstrates the usage of Twain scanning in a typical WPF application:

  • Scanning with and without scanner UI
  • Display of multiple scanned images in WPF
  • Upload of image to server using web services

Background

Twain is a widely used software standard common in acquisition of images from scanners and cameras.

The Twain interface is defined using low-level windows with a vast usage of unmanaged pointers, windows handles and messages.

In 2001, a CodeProject article introduced TwainLib - a C# wrapper around the Twain interface. This code has been a reference to many published works. Unfortunately the TwainLib interface still relies on handles, explicit messages and extensive use of GDI.

It was desirable to hide these implementation details from the WPF application. Abstracting out the low level windows stuff makes the resulting code cleaner and simplifies utilization of WPF features.

The current interface class WpfTwain is built on top of the classic TwainLib interface. It handles the integration of the Twain message loop into the WPF system and uses managed BitmapSource instead of GDI+ used in TwainLib.

Using the Code

The interface class to be used by the WFP is WpfTwain.

Acquiring an image is done in the following steps:

  1. Create the interface object, typically in the MainWindow Load event
  2. Select Twain source (not necessary if only one Twain source is defined in your system)
  3. Initiate acquisition
  4. Process acquisition results event

All these steps are straightforward and intuitive. See the MainWindow.cs code in the demo application for a complete sample.

1. Creating the Interface Object

C#
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    TwainInterface = new WpfTwain();
    TwainInterface.TwainTransferReady += new TwainTransferReadyHandler
					(TwainWin_TwainTransferReady);

    ...
}		

Upon creation, the Twain interface will internally hook message and take care for implementation details.

Notice we register to one event - TwainTransferReady. This will allow us to process acquired images.

It is also possible to hook to additional events, but it is not necessary for a simple acquisition. If you need finer-grain low level control over the process, please see the WpfTwain class implementation. Probably not needed in most cases.

2. Selecting a Source

C#
private void SelecctButton_Click(object sender, RoutedEventArgs e)
{
    TwainInterface.Select();
}	

This is self explanatory, isn't it? Calling the Select method of the Twain interface will cause the Twain source selection dialog to pop. This is a windows dialog and is controlled by the Twain system.

3. Starting a Scan

C#
private void ScanButton_Click(object sender, RoutedEventArgs e)
{
    TwainInterface.Acquire(false /*show UI*/);
}		

The only thing to mention is the showUI argument. Setting it to true will cause the acquisition window to show. This window is specific to the device (installed by the device driver) so its appearance and behavior is different from device to device.

In some cases (e.g. where automation is desired), it is preferable to hide this and just run the scan. The demo application provides both options.

4. Processing Scan Results

C#
private void TwainWin_TwainTransferReady(WpfTwain sender, List<ImageSource> imageSources)
{
    foreach (ImageSource ims in imageSources)
        AddImageThumbnail(ims); // process the image by the application

    // alternatively if the program should only support one-image scans
    // you can use imageSources[0]
    this.Activate();
}		

This event handler receives the list of images acquired and does whatever the application needs.

That's it. This is all that is needed to successfully run scanners and get images from WPF.

The Demo Application

The demo application utilizes some cool WPF features, just to remind us why we wanted to use WPF in the first place.

1. Multiple Image Support

Scan Application

The program displays a list of image thumbnails and a larger selected image. When a new image is acquired, it is added to the list of thumbnails.

Each thumbnail is actually a WPF button. Clicking a button opens up the corresponding image in a full view.

The boundary between the thumbnails and the full-view image can be moved. Doing so changes the width of the thumbnail area. The sizes of the thumbnails and the full image are automatically adjusted. This is all done by the WPF engine - no coding required.

Here is the XAML behind the auto-sizing thumbnails:

XML
<Border BorderThickness="1" BorderBrush="#FF6E789A" Margin="12,70,12,12" >
<Grid  Name="imageGrid"><Grid.ColumnDefinitions><ColumnDefinition Width="75" />
<ColumnDefinition Width="5" /><ColumnDefinition Width="*" />
</Grid.ColumnDefinitions><GridSplitter HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch"
                  Grid.Column="1" ResizeBehavior="PreviousAndNext"
                  Width="Auto" Background="#FF787896" Height="Auto" />
                  <ScrollViewer VerticalScrollBarVisibility="Auto">
                  <StackPanel Margin="0,0,0,0" Name="ThumbnailStackPanel" >
                        <button
    height="Auto" width="Auto"><Button.Content>
                                <Image HorizontalAlignment="Left" Stretch="Uniform"
                                VerticalAlignment="Top"
                                Source="/scan2web;component/Resources/
				free-drink-pictures-espresso-coffee.jpg" />
                            </Button.Content>
                        </button></StackPanel>
                </ScrollViewer>
                <Image  Grid.Column="2" HorizontalAlignment="Left" Name="image1"
                Stretch="Uniform" VerticalAlignment="Top"
                Source="/scan2web;component/Resources/
			free-drink-pictures-espresso-coffee.jpg" />
            </Grid>
        </Border>

Scanning adds images, pressing clear clears all thumbnails.

The following is a screen capture with the slider moved to the right. Note that the thumbnail buttons are stretched to fit the width, and in addition, a vertical scroller is automatically added.

App - wider thumbnails

Note: Images for the above were acquired using Teac mx-10 webcam.

2. Upload an Image to a Web Server

In many applications, it is required to provide scanner automation where scanning and uploading to a web server is done in one click.

Code for uploading an image and the corresponding server side are provided to complete this sample. Note that C# 4 has changed the service proxy, here the client side uses a C# 2 style web service proxy for wider compatibility.

Client side is as follows:

C#
public void UploadImage()
{
    MemoryStream stream = new MemoryStream();
    try {
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        // TBD: encoding parameters (quality etc.)

        TextBlock myTextBlock = new TextBlock();
        BitmapSource bs = image1.Source as BitmapSource;
        BitmapFrame bf = BitmapFrame.Create(bs);
        //encoder.Frames.Add(BitmapFrame.Create(image1.Source));
        encoder.Frames.Add(bf);
        encoder.Save(stream);
        stream.Flush();

        // upload
        scan2web.ScanServer.Scanner scanerServerProxy =
        			new scan2web.ScanServer.Scanner();
        string result = scanerServerProxy.UploadScan
        		(stream.GetBuffer(), "test 1");
        UploadResultLabel.Content = result;
    } catch (Exception ex) {
    UploadResultLabel.Content = "Error: " + ex.Message;
    }
    stream.Close();
    // This will come handy if we want to annotate the image
    //RenderTargetBitmap rendered = new RenderTargetBitmap
    ( (int)bs.Width, (int)bs.Height, bs.DpiX, bs.DpiY, bs.Format);
    //rendered.Render(image1);
} 

The code uses web method to upload the current image as an array of bytes. Additional arguments can be sent to complete the information - as relevant to your application.

And the corresponding server side is:

C#
[WebMethod]
public string UploadScan(byte[] data, string scanKey)
{
    Guid fileID = Guid.NewGuid();
    string path = Server.MapPath("~/Documents");
    string filePath = path + "/" + fileID.ToString() + ".jpg";
    try {
        // TBD: folder by date of upload to prevent too many files in the uploads folder
        FileStream traget = new FileStream
        	(filePath, FileMode.Create); // the jpg extension is for debug
        traget.Write(data, 0, data.Length);
        traget.Flush();
        traget.Close();
        // TBD: register in the DB (fileID, scanKey, person, date etc)
    } catch (Exception ex) {
    // TBD: cleanup - delete file, clear DB atc.
    // TBD: register the error and alert operators
    return "Error: " + ex.Message;
    }
    return "Saved";
}

Points of Interest

This project was a practical exercise in abstraction, particularly meant to simplify usage of Twain by removing low level details from the client code.

Most of the effort did not go to the application but rather to figuring out ways to activate the legacy code, translate bitmaps, etc. I hope this can be saved from developers interested in Twain by using this code.

This code was tested on a few computers with 32bit and 64bit OS and a few types of sources:

  1. Teac MX-10 webcam (using twain interface)
  2. HP LaserJet 3055 multi purpose device (using both Twain and Twain over WIA)
  3. Brother MFC-6490W multi purpose scanner
  4. Canon Lide 100

We are not aware of any problems, however testing was limited.

Limitations

The current code does not utilize many of the more advanced Twain capabilities. Using such capabilities (for example multi-page scan) was out of the scope of this project.

Feedback

Any feedback, requests, problems, suggestions, fixes and improvements will be highly welcomed..

Please contact Baruch at rnd@ibn-labs.com for requests and comments.

History

  • 21st March, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer IBN Labs Ltd
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: error when i run my app Pin
Member 107273886-Apr-14 11:17
Member 107273886-Apr-14 11:17 
GeneralRe: error when i run my app Pin
Baruch236-Apr-14 12:42
professionalBaruch236-Apr-14 12:42 
QuestionHow can i scan multi pages Pin
Member 397326719-May-13 17:45
Member 397326719-May-13 17:45 
AnswerRe: How can i scan multi pages Pin
Baruch2320-Nov-13 21:56
professionalBaruch2320-Nov-13 21:56 
GeneralRe: How can i scan multi pages Pin
z1h2u3q426-Jun-14 20:35
z1h2u3q426-Jun-14 20:35 
GeneralMy vote of 5 Pin
Prasad Khandekar17-Apr-13 9:19
professionalPrasad Khandekar17-Apr-13 9:19 
GeneralRe: My vote of 5 Pin
Baruch2317-Apr-13 20:58
professionalBaruch2317-Apr-13 20:58 
Questionrunning sharpdevelop 4.X: error System.Runtime.InteropServices.SEHException: Pin
e_matrix16-Mar-13 17:04
e_matrix16-Mar-13 17:04 
AnswerRe: running sharpdevelop 4.X: error System.Runtime.InteropServices.SEHException: Pin
e_matrix16-Mar-13 19:09
e_matrix16-Mar-13 19:09 
GeneralMy vote of 5 Pin
abdusalam.benhaj1-Jan-13 21:42
abdusalam.benhaj1-Jan-13 21:42 
GeneralRe: My vote of 5 Pin
Baruch232-Jan-13 1:41
professionalBaruch232-Jan-13 1:41 
QuestionClose Scanner GUI does not work Pin
kada1235-Nov-12 22:01
kada1235-Nov-12 22:01 
AnswerRe: Close Scanner GUI does not work Pin
Baruch236-Nov-12 4:09
professionalBaruch236-Nov-12 4:09 
GeneralRe: Close Scanner GUI does not work Pin
kada1238-Nov-12 22:35
kada1238-Nov-12 22:35 
GeneralMy vote of 5 Pin
Mario Majčica21-Oct-12 5:42
professionalMario Majčica21-Oct-12 5:42 
GeneralRe: My vote of 5 Pin
Baruch2322-Oct-12 8:20
professionalBaruch2322-Oct-12 8:20 
QuestionNeed to set size setting in twain Pin
Parekh Vishal31-Jul-12 19:12
Parekh Vishal31-Jul-12 19:12 
QuestionHide progress bar window Pin
Member 46759534-Jun-12 21:15
Member 46759534-Jun-12 21:15 
QuestionNeed to set default parameter in twain UI Pin
Parekh Vishal25-May-12 23:18
Parekh Vishal25-May-12 23:18 
QuestionHide progress indicator Pin
gnpc2210-Apr-12 8:08
gnpc2210-Apr-12 8:08 
GeneralMy vote of 5 Pin
Steve Maier5-Apr-12 4:43
professionalSteve Maier5-Apr-12 4:43 
Questionsilverlight Pin
sridharsr25-Mar-12 4:44
sridharsr25-Mar-12 4:44 
QuestionAttempted to divide by zero Pin
appalanaidu Aug20117-Feb-12 19:30
appalanaidu Aug20117-Feb-12 19:30 
Questionreat functionality but something is not working for me... Pin
mosquets16-Aug-11 21:45
mosquets16-Aug-11 21:45 
AnswerRe: reat functionality but something is not working for me... Pin
Baruch2317-Aug-11 12:16
professionalBaruch2317-Aug-11 12:16 
Hello,

Unfortunately it is very difficult to guess the reason for the problem without some hands-on debugging.

The biggest difference between WPF and windows application would be the message processing so I would look there first.

Then I would check with different computer-OS-scanner combinations and see which works.
This should give some clues to the problem and possibly help with the fix.

Another thing to observe would be the exact behavior of the Twain buttons: can you select source?
can you activate the UI? scan without UI?

If that will not help you can always contact me on rnd@ibn-labs.com for commercial support.

Good luck
Baruch

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.