Click here to Skip to main content
15,861,125 members
Articles / Programming Languages / C#
Article

WIA Scripting and .NET

Rate me:
Please Sign up or sign in to vote.
4.90/5 (114 votes)
19 May 2002Public Domain5 min read 2M   57.9K   334   317
How to use Windows Image Acquisition on Windows XP. Useful for integrating scanners, digital cameras, webcams and still-video.

Sample Image - wiascriptingdotnet.jpg

Disclaimer: The information in this article & source code are published in accordance with the final [V1] bits of the .NET Framework

Abstract

This sample shows how to use Windows XP Windows Image Acquisition (WIA) Scripting with .NET and C#. It is useful for integrating with scanners, digital cameras, webcams and still-video.

Note, this article doesn't save you from reading the detailed WIA documentation!

WIA

WIA is a standardized Win32 API for acquiring digital images from devices that are primarily used to capture still images, and for managing these devices. WIA was introduced with Windows Millennium and updated for Windows XP. Today, most digital imaging devices are supported on XP by built-in or manufacturer provided WIA drivers.

The API is exposed as COM interfaces, in two flavors:

  • WIA custom interfaces - mainly for C++ programmers.
  • WIA Scripting Model - designed for scripting languagues and it provides a type library.

A seamless and low-effort integration with .NET is (currently) only possible with WIA Scripting.

WIA Scripting

The WIA Scripting Model is described in the WIA Scripting reference on MSDN Platform SDK. The typical steps needed to acquire an image are as follows:

  • Create the WIA Manager COM object.
  • With the help of the WIA manager, let the user select an imaging device (scanner/camera/...).
  • The selected device gets accessible as a new WIA root device item (another COM object).
  • With this device item, we present a GUI dialog to the user for picking up pictures.
  • These pictures get accessible as a collection of WIA image items.
  • Finally, we can transfer each of these image items e.g. to disk files!

With pseudo code this looks as simple as:

C#
manager = new Wia
root = manager.Create
collection = root.GetItemsFromUI
collection[0..n].Transfer

WIA provides its own common dialogs to select a device:

WIA device selection dialog box

and e.g. dialogs specific to a scanner device, ... or specific to a photo camera device:

WIA common dialogs to define images

Note, some tasks are also possible without user (GUI) interaction. One such method is Item.TakePicture but you should check the documentation for a complete list.

The WIA Scripting Model organizes all known items (devices, folders, pictures,...) in a hierarchical structure, e.g.: WIA Camera Tree. An advanced application can recursively enumerate this tree using the Item.Children property:

C#
root                             e.g. Camera Device
+root.Children
     item1
     item2                       e.g. Folder
     +item2.Children
           item21                e.g. Picture1
           item22                e.g. Picture2

Code

To use WIA Scripting in your Visual Studio .NET project, add a reference to the component "Microsoft Windows Image Acquisition 1.01 Type Library" (wiascr.dll)

WIA Scripting COM component reference with VS.NET

Without VS.NET, you will have to use the TLBIMP tool.

Now you can add the WIA Scripting namespace at the top of your C# code file:

C#
using System.IO;
using System.Runtime.InteropServices;

// namespace of imported WIA Scripting COM component
using WIALib;

This imported library namespace provides mapping of the WIA Scripting types to .NET wrapper classes:

  • Wia => WiaClass
  • DeviceInfo => DeviceInfoClass
  • Item => ItemClass
  • Item.Children => CollectionClass

and now you can write code like this simplified sample to acquire pictures:

C#
// create COM instance of WIA manager
wiaManager = new WiaClass();		
	
object selectUsingUI = System.Reflection.Missing.Value;

// let user select device
wiaRoot = (ItemClass) wiaManager.Create( 
    ref selectUsingUI );  

// this call shows the common WIA dialog to let 
// the user select a picture:
wiaPics = wiaRoot.GetItemsFromUI( WiaFlag.SingleImage,
    WiaIntent.ImageTypeColor ) as CollectionClass;

// enumerate all the pictures the user selected
foreach( object wiaObj in wiaPics )      
{
    wiaItem = (ItemClass) Marshal.CreateWrapperOfType( 
        wiaObj, typeof(ItemClass) );

    // create temporary file for image
    imageFileName = Path.GetTempFileName();      
    
    // transfer picture to our temporary file
    wiaItem.Transfer( imageFileName, false );             
}

For more information on COM interop and WIA debugging read these two articles:

Asynchronous Transfer and Events

Some devices, especially photo-cameras on serial COM ports, are slow! So it will take many seconds to transfer pictures. WIA Scripting solves this issue with an asynchronous flag when using Item.Transfer:

C#
// asynchronously transfer picture to file
wiaItem.Transfer( imageFileName, true );

To notify the application about the completed transfer and more, the WIA manager exposes three events:

  • OnTransferComplete - file transfer completed
  • OnDeviceDisconnected - a device was e.g. unplugged
  • OnDeviceConnected - a new device was connected

These events nicely map on to the .NET event/delegate model, so we add a handler function like so:

C#
// delegate member variable
private _IWiaEvents_OnTransferCompleteEventHandler 
    wiaEvtTransfer;
...

// create event delegate
wiaEvtTransfer = new _IWiaEvents_OnTransferCompleteEventHandler(
                         this.wia_OnTransferComplete );

// subscribe to event
wiaManager.OnTransferComplete += wiaEvtTransfer;
...

// event handler function (callback from WIA!)
public void wia_OnTransferComplete( 
    WIALib.Item item, string path )
{
  ... // logic to handle completed transfer
}

Video

For web cams or other video devices, WIA on Windows XP has a great new feature: live video stream overlay! It uses DirectShow to draw the overlay on the graphics card. The IWiaVideo interface can be accessed by importing another COM type library: "WiaVideo 1.0 Type Library" (wiavideo.dll). Unfortunately, the embedded TLB has a bug for methods passing a window handle. I used ILDASM to get the IL code of the interop assembly, then I changed all incorrect occurances of 'valuetype _RemotableHandle&' to 'native int', then finally compiled back to an assembly with ILASM. This repaired DLL is included in the download as WIAVIDEOLib.dll.

The code to show a real-time and live video stream in a window could be as simple as these two steps:

C#
wiaVideo = new WiaVideoClass();
wiaVideo.CreateVideoByWiaDevID( 
    wiaDeviceID, window.Handle, 0, 1 );

and to take a snapshot jpeg image from the current video stream is possible with one single method:

C#
// this string will get the filename of the picture...
string jpgFile;            

// call IWiaVideo::TakePicture
wiaVideo.TakePicture( out jpgFile );

Check the included video sample for more!

Samples

Full source code with Visual Studio .NET projects are provided for these samples:

  • WiaEasyImage very simple application to access WIA scanners and cameras.
  • WiaEasyVideo application only using WIA video devices, does show live video stream overlay.
  • WiaScriptSample advanced application using most of WIA Scripting functions.

Limitations

  • Again, for Windows XP only! if you need .NET imaging for older systems, try this TWAIN sample
  • Windows ME has an older version of WIA, but you can't use the same code/type-lib from these samples for that version.
  • WIA devices must be fully detected and configured by Windows.
  • As far as I know, WIA needs your app to have the [STAThread] attribute on the Main() method used to launch your application.
  • Item.Thumbnail was left out as it uses an undocumented Asynchronous Pluggable Protocol (APP) and has bugs.
  • Code was only tested with an Olympus digi-cam, an Epson scanner, a Logitech QuickCam, and a Sony DV CamCorder.

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

 
QuestionADF Scanning Pin
ivo753-Jul-11 2:46
ivo753-Jul-11 2:46 
GeneralProgressCallback Pin
JDHoster10-May-11 19:46
JDHoster10-May-11 19:46 
GeneralMy vote of 5 Pin
Member 77964406-Apr-11 10:54
Member 77964406-Apr-11 10:54 
Questionit dos not work in windows 7 Pin
sina tarkesh18-Jan-11 22:22
sina tarkesh18-Jan-11 22:22 
AnswerRe: it dos not work in windows 7 Pin
njdnjdnjdnjdnjd22-Jan-11 11:18
njdnjdnjdnjdnjd22-Jan-11 11:18 
AnswerRe: it dos not work in windows 7 Pin
Camilo Sanchez5-Oct-11 9:37
Camilo Sanchez5-Oct-11 9:37 
GeneralMy vote of 1 Pin
Sammy Hale15-Dec-10 7:07
Sammy Hale15-Dec-10 7:07 
GeneralRe: My vote of 1 Pin
njdnjdnjdnjdnjd13-Jan-11 8:21
njdnjdnjdnjdnjd13-Jan-11 8:21 
The WIA scripting application will not build if running visual studio on windows 7 (I guess the same applies to Vista). To run and build the application you need to utilise visual studio on Windows XP.
GeneralWIA for Windows 7 Pin
Sérgio Pitta9-Nov-10 6:53
Sérgio Pitta9-Nov-10 6:53 
GeneralRe: WIA for Windows 7 Pin
kdeenihan12-Nov-10 1:05
kdeenihan12-Nov-10 1:05 
AnswerRe: WIA for Windows 7 Pin
NETMaster12-Nov-10 6:12
NETMaster12-Nov-10 6:12 
QuestionWia Scripting Pin
krutipathak25-Oct-10 21:53
krutipathak25-Oct-10 21:53 
Generalproblem with this scripting wia sample Pin
essanawras2-Aug-10 10:25
essanawras2-Aug-10 10:25 
GeneralPlease correct URLes Pin
piotr_t18-May-10 22:16
piotr_t18-May-10 22:16 
GeneralCan't get scanner to use Document Feeder Pin
pattyweb19-Mar-10 11:39
pattyweb19-Mar-10 11:39 
QuestionAbout "Not Detecting Scanner " Pin
NitinMakwana9-Feb-10 20:25
NitinMakwana9-Feb-10 20:25 
QuestionHRESULT: 0x80210015 Pin
Atomosk18-Jan-10 19:40
Atomosk18-Jan-10 19:40 
AnswerRe: HRESULT: 0x80210015 Pin
nhn9916-Apr-10 13:46
nhn9916-Apr-10 13:46 
AnswerRe: HRESULT: 0x80210015 Pin
avrilxu22-Apr-10 15:49
avrilxu22-Apr-10 15:49 
AnswerRe: HRESULT: 0x80210015 Pin
bob11229-May-10 5:20
bob11229-May-10 5:20 
GeneralAutofous Camera WIA Scripting and .NET Pin
Member 48506930-Dec-09 19:02
Member 48506930-Dec-09 19:02 
QuestionHow to implement this in to the Asp.net Pin
rajan418@hotmail.com30-Dec-09 1:48
rajan418@hotmail.com30-Dec-09 1:48 
AnswerRe: How to implement this in to the Asp.net Pin
ahmed_zgfci20-Dec-11 1:46
ahmed_zgfci20-Dec-11 1:46 
Generalfeeder scanner Pin
eng walaa anwar28-Dec-09 23:27
eng walaa anwar28-Dec-09 23:27 
GeneralCant download the source code Pin
soft.sri8127-Dec-09 0:48
soft.sri8127-Dec-09 0:48 

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.