Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Twain for WPF Applications - Look Ma, No Handles

0.00/5 (No votes)
22 Mar 2011 3  
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

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

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

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

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:

<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:

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:

[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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here