Geeks With Blogs

News

View Anthony Trudeau's profile on LinkedIn

Add to Technorati Favorites


Anthony Trudeau

I was playing around this morning with scanning images and put together an adapter class that uses the Windows automation library (WIAAUT.DLL) which is part of the WIA automation SDK -- WIA means Windows Image Acquisition.

Here are the imports I used for the code file:

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using WIA;

I created a simple enumeration for some of the more common errors that I expected.

public enum WiaScannerError : uint
{
     LibraryNotInstalled = 0x80040154,
     OutputFileExists = 0x80070050,
     ScannerNotAvailable = 0x80210015,
     OperationCancelled = 0x80210064
}

Instead of throwing a COMException I created a special exception class that provides an error code from the aforementioned enumeration.

[Serializable]
public class WiaOperationException :
Exception
{
     private WiaScannerError _errorCode;

     public WiaOperationException(WiaScannerError errorCode)
          : base()
     {
          ErrorCode = errorCode;
     }

     public WiaOperationException(string message, WiaScannerError errorCode)
          : base(message)
     {
          ErrorCode = errorCode;
     }

     public WiaOperationException(string message, Exception innerException)
          : base(message, innerException)
     {
          COMException comException = innerException as COMException;

          if (comException != null)
               ErrorCode = (WiaScannerError)comException.ErrorCode;
     }

     public WiaOperationException(string message, Exception innerException, WiaScannerError errorCode)
          : base(message, innerException)
     {
          ErrorCode = errorCode;
     }

     public WiaOperationException(System.Runtime.Serialization.SerializationInfo info, 
          System.Runtime.Serialization.StreamingContext context)
               : base(info, context)
     {
          info.AddValue("ErrorCode", (uint)_errorCode);
     }

     public WiaScannerError ErrorCode
     {
          get { return _errorCode; }
          protected set { _errorCode = value; }
     }

     public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context)
     {
          base.GetObjectData(info, context);
          ErrorCode = (WiaScannerError)info.GetUInt32("ErrorCode");
     }
}

The actual class I created is just for scanners, but you can adapt it to any device that supports WIA.  I've pulled out comments and removed some extra stuff like providing a friendly message for errors for the sake of brevity.

public sealed class WiaScannerAdapter : IDisposable
{
     private CommonDialogClass _wiaManager;
     private bool _disposed;
// indicates if Dispose has been called

 
    public WiaScannerAdapter()
     {
     }

     ~WiaScannerAdapter()
     {
          Dispose(false);
     }

     private CommonDialogClass WiaManager
     {
          get { return _wiaManager; }
          set { _wiaManager = value; }
     }

     [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
     public Image ScanImage(ImageFormat outputFormat, string fileName)
     {
          if (outputFormat == null)
               throw new ArgumentNullException("outputFormat");

          FileIOPermission filePerm =
               new FileIOPermission(FileIOPermissionAccess.AllAccess, fileName));
          filePerm.Demand();

          ImageFile imageObject = null;

         
try
         
{
               if (WiaManager == null)
                    WiaManager = new CommonDialogClass();

               imageObject =
                    WiaManager.ShowAcquireImage(WiaDeviceType.ScannerDeviceType,
                         WiaImageIntent.ColorIntent, WiaImageBias.MinimizeSize, 
                         outputFormat.Guid.ToString("B"), false, true, true);

               imageObject.SaveFile(fileName);
               return Image.FromFile(fileName);
          }
          catch (COMException ex)
          {
               string message = “Error scanning image“;
               throw new WiaOperationException(message, ex);
          }
         
finally
         
{
               if (imageObject != null)
                    Marshal.ReleaseComObject(imageObject);
          }
     }

     public void Dispose()
     {
          Dispose(true);
          GC.SuppressFinalize(this);
     }

     private void Dispose(bool disposing)
     {
          if (!_disposed)
          {
               if (disposing)
               {
                   
// no managed resources to cleanup
               
}

             
// cleanup unmanaged resources
             
if (_wiaManager != null)
                   Marshal.ReleaseComObject(_wiaManager);

              _disposed = true;
          }
     }
}

Calling the adapter is really easy.  Here's an example that puts the image into a picturebox:

using (WiaScannerAdapter adapter = new WiaScannerAdapter())
{
    
try
    
{
          Image image = adapter.ScanImage(ImageFormat.Bmp, @"c:\temp\test.bmp");
          pictureBox1.Image = image;
     }
     catch (WiaOperationException ex)
     {
          MessageBox.Show(ex.Message + “ Error Code: “ + ex.ErrorCode);
     }
}

Posted on Saturday, July 29, 2006 10:33 AM .NET | Back to top


Comments on this post: Using WIA for scanning

# re: Using WIA for scanning
Requesting Gravatar...
Hi,
I try to take photo from my QuickCam using WIA, but i don't succeed to set the default size of capture ...

Do you know an issue to do it ?
Regards
Left by shinji_rem on Aug 11, 2006 8:43 AM

# re: Using WIA for scanning
Requesting Gravatar...
Quickcam's WIA support is quite frankly terrible. Even in a normal application such as mspaint it won't go above its minimum resolution.
Left by Pug on Sep 25, 2006 5:22 AM

# re: Using WIA for scanning
Requesting Gravatar...
hi tony-

since i'm just getting started in both C# and WIA 2.0, would you please provide a more complete example of getting a scanned image from scanner to picturebox using your adapter?
from initializing the device, all the way through to viewing the image on-screen?

thanks ever so much.

-kevon
Left by Kevon Ward on Apr 17, 2007 8:04 AM

# re: Using WIA for scanning
Requesting Gravatar...
What didn't work or wasn't complete about it? That's all you should have to do. Anything else is going to depend on your application, frameworks, UIs, etc. that you use.
Left by Anthony Trudeau on Apr 17, 2007 10:36 AM

# re: Using WIA for scanning
Requesting Gravatar...

Hi,

How can I use the code sample inside Microsoft Access 2003.

I want to scan images from my scanner and sometimes from a digital camera into an Access form.


Thanks.
Left by Ahmad Wali Zahid on May 28, 2007 7:27 AM

# re: Using WIA for scanning
Requesting Gravatar...
i get this library not installed error message, pls wat brings about it and wat can i do
Left by AK on Sep 24, 2007 11:03 AM

# re: Using WIA for scanning
Requesting Gravatar...
Gracias... este ejemplo esta muy facil de enterder... me funciono a la perfeccion
Left by Jorge on Oct 09, 2007 7:13 PM

# re: Using WIA for scanning
Requesting Gravatar...
Any idea how to register a WIA Event to receive a call-back when a picture is taken on a camera? It appears only 3 events are exposed by interop - camera connect, disconnect, and transfer completed.

Thanks.
Left by Ron Redmer on Oct 30, 2007 10:07 AM

# re: Using WIA for scanning
Requesting Gravatar...
More information... in the ActiveX world, you would register these events this way:

'Register event for picture taken
wia.RegisterEvent wiaEventDeviceConnected, "*" 'Register event for camera connected
wia.RegisterEvent wiaEventDeviceDisconnected, "*" 'Register event for camera disconnected
wia.RegisterEvent wiaEventItemCreated, wiaAnyDeviceID


I'm not sure how to register the wiaEventItemCreated event in .NET...

Thanks!
Left by Ron Redmer on Oct 30, 2007 10:17 AM

# re: Using WIA for scanning
Requesting Gravatar...
Use the Miscellaneous.wiaAnyDeviceID for the handle and then add an event handler for the OnEvent method of the DeviceManager.

I haven't tested this, but I think it'll work.
Left by Anthony Trudeau on Oct 30, 2007 10:53 AM

# re: Using WIA for scanning in MS Access
Requesting Gravatar...
I also like to know if you have example for MS Access. I am writing small application where each record can have image, which can be scanned from scanner in a click of a button without going thru many other interfaces.

many thanks in advance.

Jay
Left by Jay on Jan 15, 2008 10:28 AM

# re: Using WIA for scanning
Requesting Gravatar...
I don't have an example that uses any flavor of VB or VBA.
Left by Anthony Trudeau on Jan 15, 2008 10:38 AM

# re: Using WIA for scanning
Requesting Gravatar...
i am looking for vb6 sample code using wia to capture and save imge file wid adf. I couldnt install MODI with office2003 as it install only MDIVWCTL.oca file which i couldnt access as component. Pls help some one as i need to capture msome multiple documents scanning.Kumar
Left by kumar on Sep 26, 2008 3:54 AM

# re: Using WIA for scanning
Requesting Gravatar...
i want to duplex scanning using WIA can u help me

Regrads,

Vijay
Left by vijay powar on Sep 22, 2009 1:25 PM

# re: Using WIA for scanning
Requesting Gravatar...
Hi,
Can u describe how to add this wia api to C# code?
Left by Riasat Abir on Nov 03, 2009 9:59 AM

# re: Using WIA for scanning
Requesting Gravatar...
Query for "WIA automation SDK" on Bing to get a download link. Download it and then install it. Then add a reference to it from the COM tab which will create an Interop assembly which you then use like any .NET assembly.
Left by Anthony Trudeau on Nov 03, 2009 10:09 AM

# re: Using WIA for scanning
Requesting Gravatar...
I have tried this code and it works great but has one really big problem. It can only produce BMP files. I know, change the ImageFormat being passed to the ScanImage method. Well, I have tried that. I tried changing it to JPEG, to GIF, to PNG. EVEY file it creates is the same exact length and an image viewer says that htey are all BMP files. I would really like to be able to make any ImageFormat file.
Left by Zack Sessions on Dec 16, 2009 12:30 PM

# re: Using WIA for scanning
Requesting Gravatar...
since i'm just getting started in both vb.net and WIA 2.0, would you please provide a more complete example of getting a scanned image from scanner to picturebox using your adapter?
from initializing the device, all the way through to viewing the image on-screen?
we are able to detect the device but facing problem in scanning.can send code for scanning.
thanks ever so much.
Left by chakraborty on Feb 25, 2010 1:15 AM

# re: Using WIA for scanning
Requesting Gravatar...
thnax for all, but i need an example of how to use WIAAUT.dll to scan a book using C# application
thnx
amr adawy
Left by Amr Adawy on Mar 24, 2010 6:48 AM

# re: Using WIA for scanning
Requesting Gravatar...
Thnax i hoope it ll work for mi...............
Left by Kuldeep on Apr 04, 2010 5:06 AM

# re: Using WIA for scanning
Requesting Gravatar...
Hi. Could you send me the project as an example, I am new using C# and I don't understand very well how to join the parts of code.

erubriago@hotmail.com
Left by Erubey on Apr 08, 2010 1:18 AM

# re: Using WIA for scanning
Requesting Gravatar...
Could you send the project also to me !
address: wmeeus@skynet.be

thanks
w
Left by ward on Jul 08, 2010 3:58 AM

# re: Using WIA for scanning
Requesting Gravatar...
hi, what should i install in other computers for the LibraryNotInstalled error???
Left by osalo on Aug 09, 2010 7:18 PM

# re: Using WIA for scanning
Requesting Gravatar...
hi, now i'm getting "Excepci├│n de HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED)" this happend when i try to scan image with high resolution... but i want to be able to do that.

how can i solve this???
Left by osalo on Aug 10, 2010 4:22 PM

# re: Using WIA for scanning
Requesting Gravatar...
THANK YOU!!
It does exactly what I've been trying to accomplish.
Left by Robert on Aug 28, 2010 10:02 PM

# re: Using WIA for scanning
Requesting Gravatar...
thanks for your example it works fine for me, but I'm facing problem after publishing, I think it is related to a permission at DCom config
any help ?
Left by Mohsen on Apr 11, 2011 11:01 AM

# re: Using WIA for scanning
Requesting Gravatar...
Excellent Starter Code!!! Thanks a million
Left by Jim on Apr 19, 2011 1:47 PM

# re: Using WIA for scanning
Requesting Gravatar...
how to delete the temp file @"c:\temp\test.bmp" ?
Left by nadeem on Feb 02, 2012 9:36 AM

Your comment:
 (will show your gravatar)


Copyright © Anthony Trudeau | Powered by: GeeksWithBlogs.net