Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

Scanning an Image from Silverlight 4 using WIA Automation

Pete Brown - 14 April 2010

Silverlight 4 Out-of-Browser apps now have the ability to be elevated trust applications, if you request it and your users consent. One of the more powerful features of trusted applications is the ability to use IDispatch COM servers on the local machine. Basically, if you can access the COM object from script, you can access it from Silverlight. That includes everything from Word and Excel automation to what we're going to tackle in this post: automating local devices.

While working on ShoeBoxScan today, I decided to try and rip out some of the scanner code and plug it into Silverlight to see if it worked, and how well it worked.

Setup

Make sure you're running Visual Studio 2010 and have the SL4 bits installed. Then create a new Silverlight 4 solution with an associated web site.

In the Silverlight project, set the project properties to mark it as an out-of-browser application

image

Then open up the out-of-browser settings dialog and mark the application as requiring elevated trust.

image

While you're at it, open up the debug tab and set your OOB app as the start action. I didn't realize this option was even here until I asked Tim Heuer if we could have it in the next version of Silverlight :) This will allow you to debug your out-of-browser application without the manual install step.

image

The screenshot above is correct, the web project is what is picked for the start action, not the Silverlight project.

Finally, since we'll be using the dynamic keyword, you'll need to add a reference to Microsoft.CSharp.dll, located in the Silverlight 4 SDK

image

Support Classes

I pulled this code from my WPF app, which is using MVVM. We'll need to add a couple little classes to support that here. Each of these support classes need to be added to your Silverlight project.

The first is the Observable class. Insert your favorite flavor of INotifyPropertyChange code here, or simply use mine:

public abstract class Observable : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

That's the base class for anything that's going to be used in binding.

Next, we'll add a simple container class for the scanned image. I did this because I didn't want to pass WIA types around in the application; I wanted them all behind the Scanner service.

class ScannerImage : Observable
{
    private BitmapSource _image;
    public BitmapSource Image
    {
        get { return _image; }
        internal set { _image = value; NotifyPropertyChanged("Image"); }
    }

}

ScannerService Class

Add a class named "ScannerService" to your Silverlight project.

We don't have access to the constants and enumerations exposed by WIA, so we need to duplicate them in our code. Luckily, the documentation has all the values we need.

Constants and Enumerations

I added the constants and enumerations as nested classes and enums in the ScannerService class

class ScannerService
{
    // http://msdn.microsoft.com/en-us/library/ms630792(v=VS.85).aspx
    private enum WiaDeviceType
    {
        UnspecifiedDeviceType = 0,
        ScannerDeviceType = 1,
        CameraDeviceType = 2,
        VideoDeviceType = 3
    }

    // http://msdn.microsoft.com/en-us/library/ms630798(v=VS.85).aspx
    private enum WiaImageIntent
    {
        UnspecifiedIntent = 0,
        ColorIntent = 1,
        GrayscaleIntent = 2,
        TextIntent = 4
    }

    // http://msdn.microsoft.com/en-us/library/ms630796(v=VS.85).aspx
    private enum WiaImageBias
    {
        MinimizeSize = 65536,
        MaximizeQuality = 131072
    }

    // http://msdn.microsoft.com/en-us/library/ms630810(v=VS.85).aspx
    private class FormatID
    {
        public const string wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}";
        public const string wiaFormatPNG = "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}";
        public const string wiaFormatGIF = "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}";
        public const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
        public const string wiaFormatTIFF = "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}";
    }


// scan method will go here

}

Scan Method

Here's the first version of the scan method. It doesn't return or convert the image, because we're just testing to see if we can invoke the WIA dialog from Silverlight.

public void Scan()
{
    try
    {
        dynamic wiaDialog = AutomationFactory.CreateObject("WIA.CommonDialog");

        dynamic imageFile = wiaDialog.ShowAcquireImage(
                (int)WiaDeviceType.ScannerDeviceType,
                (int)WiaImageIntent.ColorIntent,
                (int)WiaImageBias.MaximizeQuality,
                FormatID.wiaFormatJPEG, false, true, false);
    }
    catch (Exception ex)
    {
        // need to do something here. Old WPF code is below
        //if (ex.ErrorCode == -2145320939)
        //{
        //    throw new ScannerNotFoundException();
        //}
        //else
        //{
        //    throw;
        //}
    }

}

Note that the casts to "int" are required to avoid a runtime exception. the COM API knows what to do with an int, but has no idea what to do with our own WiaDeviceType and other enums

ViewModel

Here's the first rev of our viewmodel. It surfaces an ImageSource, but we won't do anything with that just yet.

public class ScannerViewModel : Observable
{
    private ImageSource _scannerImage;
    public ImageSource ScannerImage
    {
        get { return _scannerImage; }
        set { _scannerImage = value; NotifyPropertyChanged("ScannerImage"); }
    }

    public void Scan()
    {
        ScannerService service = new ScannerService();
        service.Scan();
    }

}

By now, you should have a project that looks something like this:

image

The next step is to slap some xaml into MainPage and then call the Scan method to test this out.

MainPage

We're at a point where we can test some basic functionality, so let's whip up some xaml and call the Scan method. We'll set up the grid so there's room for the image, but for now, all we'll have is a single Scan button.

<UserControl x:Class="PeteBrown.SilverlightScannerDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="478" d:DesignWidth="650">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        
        <Button x:Name="Scan"
                Content="Scan"
                Width="100"
                Height="30"
                Margin="10"
                Grid.Row="1" />
    </Grid>
</UserControl>

In the code behind (no commands in this demo, but you can find info on them here and elsewhere) I wire up both the loaded event to set the datacontext (used later) and the click event for the scan button.

public partial class MainPage : UserControl
{
    private ScannerViewModel _viewModel = new ScannerViewModel();

    public MainPage()
    {
        InitializeComponent();

        Loaded += new RoutedEventHandler(MainPage_Loaded);
        Scan.Click += new RoutedEventHandler(Scan_Click);
    }

    void Scan_Click(object sender, RoutedEventArgs e)
    {
        _viewModel.Scan();
    }

    void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        DataContext = _viewModel;
    }
}

Running the App

Run the app and click the "Scan" button. If you have a recognized WIA-compatible scanner attached, you'll get the scan dialog:

image

Yes, from frickin Silverlight! Pretty awesome :)

 

Converting the WIA Image to a Bitmap Silverlight Understands

The code here converts from the WIA image type to something Silverlight will understand. There is an in-memory way to do the conversion, but you overrun the limits of the core COM types if you work with a large image (like a 1200dpi scan). Unfortunately, Silverlight 4 doesn't let you use the Path.GetTempFileName API, and doesn't include the BitmapFrame type, so I can't use the same code as the WPF version. That said, I can come close.

The main issue I ran into was with the file format used by WIA when saving images. Even though we specified "JPEG" in the scanning format, WIA saves to a bitmap. I found this out when I kept getting catastrophic failures trying to use the stream as an image source. I went and looked at the temp files, and they were all the same size. Cracked one open in notepad and I saw the BMP file header.

Silverlight doesn't understand the BMP file format. Luckily, Joe Stegman has created a BMP Decoder sample we can use.

WiaImageFileToBitmap Method

This method handles getting the bits from the scanned image and transforming them into a BitmapSource for use in Silverlight.

private BitmapSource WiaImageFileToBitmap(dynamic imageFile)
{
    if (imageFile == null)
        return null;

    // I hate to stick temp files in MyDocuments, but that's the only real option here
    string filepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string name = "Scan_" + Guid.NewGuid().ToString() + ".jpg";
    string filename = filepath + @"\" + name;
            
    // WIA saves in bitmap format
    imageFile.SaveFile(filename);

    WriteableBitmap bitmap;

    using (FileStream stream = File.OpenRead(filename))
    {
        Texture tex = BMPDecoder.Decode(stream);
        bitmap = tex.GetWriteableBitmap();
        stream.Close();
    }

    // cleanup
    File.Delete(filename);

    return bitmap;
}
The Bitmap Decoder

I snagged the bitmap decoder from Joe Stegman's blog as mentioned above. Other than changing the namespace, I made no changes to the source.

image

 

Changes to the Scan method

We'll also need to change the Scan method to use the new conversion and actually return the image.

public ScannerImage Scan()
{
    try
    {
        dynamic wiaDialog = AutomationFactory.CreateObject("WIA.CommonDialog");

        dynamic imageFile = wiaDialog.ShowAcquireImage(
                (int)WiaDeviceType.ScannerDeviceType,
                (int)WiaImageIntent.ColorIntent,
                (int)WiaImageBias.MaximizeQuality,
                FormatID.wiaFormatJPEG, false, true, false);

        ScannerImage image = new ScannerImage();
        image.Image = WiaImageFileToBitmap(imageFile);

        return image;
    }
    catch (Exception ex)
    {
        //if (ex.ErrorCode == -2145320939)
        //{
        //    throw new ScannerNotFoundException();
        //}
        //else
        //{
        //    throw;
        //}

        throw;
    }

}
ViewModel update

Update the Scan method in the view model as well.

public class ScannerViewModel : Observable
{
    private ImageSource _scannerImage;
    public ImageSource ScannerImage
    {
        get { return _scannerImage; }
        internal set { _scannerImage = value; NotifyPropertyChanged("ScannerImage"); }
    }

    public void Scan()
    {
        ScannerService service = new ScannerService();
        ScannerImage image = service.Scan();

        if (image != null)
        {
            ScannerImage = image.Image;
        }
        else
        {
            ScannerImage = null;
        }
    }

}
UI Change

The final change is to the UI to bind the image

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
        
    <Image x:Name="ScannedImage"
            Source="{Binding ScannerImage}"
            Stretch="Uniform" />
        
    <Button x:Name="Scan"
            Content="Scan"
            Width="100"
            Height="30"
            Margin="10"
            Grid.Row="1" />
</Grid>

End Result

Once you have all the bits in place, run the app again. Here's what mine looks like, with an image hot off my scanner:

image 

Conclusion

If you're building a Silverlight app, and want to do a little local Scanner integration, it's certainly possible. While it takes a bit more work than doing the same thing in WPF, once you wrap the code in a nice class, it's pretty easy to use.

Make sure that your own implementation includes some checks to make sure you are running with elevated permissions. Set it up so it fails gracefully, and you'll have a nice little light-up feature for your Windows users.

         

Source Code and Related Media

Download /media/56111/petebrown.silverlightscannerdemo.zip
posted by Pete Brown on Wednesday, April 14, 2010
filed under:          

63 comments for “Scanning an Image from Silverlight 4 using WIA Automation”

  1. Petesays:
    @bruno

    I spoke with some folks on the product team, and they said the error is coming from COM.

    Do you have a WIA-compatible scanner attached? What operating system are you running? (Version and 32 or 64 bit)

    What statement is throwing the error?

    Pete
  2. Mehmetsays:
    Hello,
    We used this feature in our project which use scanner to scan a document. When we run the project in oob mode at windows 7 it works. But when we run the project in other PCs Windows XP etc. it doesnt work.
    As i know it should be platform indepented. But an error occuringin at XP OS. Could you tell me what is wrong in our project?
  3. Tomsays:
    Thanks for the great article. When I run it it Mirrors the scan??? Both left right and top bottom.

    Also the function Read24BitBmp() was throwing errors until I added

    if (header.Height < 0)
    header.Height = -header.Height;

    Just before creating the texture.

    Any Ideas????
  4. helimesays:
    Hello I have read your article and followed all steps.However,I had a lot of errors that i can not handle.If you have ready program.Send me,please .My email mhelime@mail.ru.I need it very much
  5. Petesays:
    I just added the source code to this article.

    I added the ability to attach zips to posts a few weeks ago, but didn't go back and update all the old postings with source.

    Pete
  6. Jonathansays:
    Actually, once you acquire the image through WIA, you can do the conversion and compression with WIA as well. Here is some sample C# Code:

    const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
    dynamic imageFile = CommonDialog.ShowAcquireImage(null, null, null, wiaFormatJPEG, false, false, false);
    if (imageFile != null)
    {

    if (imageFile.FormatID != wiaFormatJPEG)
    {
    dynamic ip = AutomationFactory.CreateObject("WIA.ImageProcess");
    ip.Filters.Add(ip.FilterInfos("Convert").FilterID);
    ip.Filters(1).Properties("FormatID").Value = wiaFormatJPEG;
    ip.Filters(1).Properties("Quality").Value = 20;
    imageFile = ip.Apply(imageFile);
    }

    BitmapImage bitmapBase = new BitmapImage();
    dynamic fileData = imageFile.FileData;
    byte[] imageData = fileData.BinaryData;
    MemoryStream ms = new MemoryStream(imageData);
    bitmapBase.SetSource(ms);
    WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapBase);
    }

    I found the built in coversion is quite bit faster for what I'm doing. Hope this helps someone.
  7. Jonathan Msays:
    great stuff guys

    @Pete or Jonathan, do you guys know how to acquire the image without the user choosing the device? I'm writing an app that will be used in a type of "kiosk" and will automatically choose the device. I have been unsuccessful at using wiaCommandTakePicture.. (the scanned image will be stored in IsolatedStorage and later sent via WCF)....ideas? Thanks
  8. Petesays:
    For those of you running into "This operation is not supported in the current context." errors, please let me know:

    - Operating system version (Win7 Ultimate, Vista Home etc.)
    - 32 or 64 bit
    - Make / Model of your scanner
    - Date of your scanner driver (obtained from the device manager in control panel)

    I'm trying to nail down the cause for that error. It comes from COM, not really from Silverlight.

    Pete
  9. aswad32says:
    i always got this error after the scanning process complete:
    server busy,
    this action cannot be completed, because the other program is busy...

    got 3 option, switch to, retry and cancel. when i click retry everything going to be fine and the image generated...

    running on win 7 64bit, scanner - Lexmark 5600 - 6600 series...

    any idea why this happen... ???

    thanks,
    aswad
  10. Lindsaysays:
    Pete, great post, thank you!

    Do you know how I can scan an image and pass that into a byte[] array?
    I don't want to save the scanned image as a bitmap file but want to write it into the db as a byte[] array.

    Many examples on the web but they're dated and none work... :-(

    Thanks,

    Lini
  11. krithikasays:
    When i execute the program example you have given, and click preview on the scan dialog. I get a "This action cannot be completed because the other program is busy. Choose switch to to activate the program and correct the problem." , when i hit switch-to the start menu is launched. I am not sure what happening, please help.!
  12. Petesays:
    @krithika

    I think that's related to the driver in-use for the scanner, but I never ran into that myself. I can't reproduce it with my Epson scanner. What make/model scanner do you use?

    @Lindsay

    There are memory constraints about going directly to a byte array. There may be some tweaks to make that more reasonable, however. I'm looking into it.
  13. krithikasays:
    Name: hp scanjet 4600
    Manufacturer: Hewlett-Packard

    When I hit preview , the ""this action.." dialog comes up , but I do see the scanner scanning and the image coming up in the interactive dialog. But the "this action.." dialog never goes away. I have to manually kill the application process.

    Can this message be supressed in code ? or is there a timeout I can specify ?
  14. Jonathan Manleysays:
    I noticed the use of the C# dynamic, how would one go about this in VB?
    I can't figure out how to take the result of ShowAcquireImage and get it to an ImageSource type
    I end up getting:
    Unable to cast object of type 'System.Runtime.InteropServices.Automation.AutomationMetaObjectProvider' to type 'System.Windows.Media.ImageSource'.
  15. ABETHANsays:
    Hi Pete,

    When I was running your code I am getting that "No object was found registered for specified ProgID." from the Line "dynamic wiaDialog = AutomationFactory.CreateObject("WIA.CommonDialog");" Could you please help me on this?

    Abe
  16. Thamysays:
    Hi Pete...

    Firstly congratz... Awsome article.
    Im trying to run it in HTML page...
    But when I click in the Scan Button i get the message: "This operation is not supported in this context"...
    Do u know if it appers because it is running in browser mode? or it should works like running in VS?

    Im using Windows XP SP2 - Scanner: HP Scanjet 4670

    Ty anyway :)
  17. Hashimsays:
    HI peter, great article
    When I click on Scan button it gives me

    [System.NotSupportedException] {System.NotSupportedException: This operation is not supported in the current context.
    at MS.Internal.Error.MarshalXresultAsException(UInt32 hr, COMExceptionBehavior comExceptionBehavior)
    at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
    at MS.Internal.ComAutomation.ComAutomationNative.CreateObject(String progID, IntPtr& nativeObject)
    at MS.Internal.ComAutomation.ComAutomationServices.CreateObject(String progID, ComAutomationParamWrapService paramWrapService)
    at System.Runtime.InteropServices.Automation.AutomationFactory.CreateObject(String progID)
    at PeteBrown.SilverlightScannerDemo.ScannerService.Scan()
    at PeteBrown.SilverlightScannerDemo.ScannerViewModel.Scan()
    at PeteBrown.SilverlightScannerDemo.MainPage.Scan_Click(Object sender, RoutedEventArgs e)
    at System.Windows.Controls.Primitives.ButtonBase.OnClick()
    at System.Windows.Controls.Button.OnClick()
    at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
    at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
    at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)} System.NotSupportedException


    This exception is raised exactly at following command
    ScannerImage image = service.Scan();

    I am using Windows Vista Home premium service pack 2, 32 bit OS
    Scanner is HP Deskjet F2180

    I will very appreciate if you reply me soon,

  18. Simhadrisays:
    Hi Pete,

    When I was running your code I am getting that "No object was found registered for specified ProgID." from the Line "dynamic wiaDialog = AutomationFactory.CreateObject("WIA.CommonDialog");" Could you please help me on this?
  19. Petesays:
    @Simhadri

    What version of Windows are you running? Do you have a scanner installed? If so, which one, and does it have WIA drivers?

    @Hashim (and others getting "operation not supported" errors)

    I'm looking into it with the WIA folks. I'm not sure when/if I'll have a response, as the root cause of the issue is unknown to me, currently.
  20. Abethansays:
    Hi Pete,

    I am using CanonScan N 650U and my operating system is XP. I have installed WIA Driver to this scanner.

    Could you pleas help me to figure out the problem?

    Thanks....
  21. Jeffsays:
    I am also getting the context error.

    Message: Unhandled Error in Silverlight Application This operation is not supported in the current context.

    Using Win7 x64, Cannon MP750 & Cannon MP210 Scanners.
    The scanners are listed in Control Panel as: WIA Canon MP750 & WIA Canon MP210
    MP750 Driver Version 10.1.0.1
    MP210 Driver Version 13.0.0.50

    Hope this helps get it resolved. This could be very useful.

    Thanks for your work.
  22. Mukesh Kumarsays:
    I think when we directly run silver light application it runs perfectly, but when we run using browser application it gives us error "This operation is not supported in the current context."

    I added a test page from where I redirected to another aspx page where silver light control is placed. And I get above error message.
  23. Petersays:
    I'm trying to find a sollution to my problem. I'm trying to implement online scanner. PC with attached scanner and IIS should distribute web application, for example: other computer in lan (computer in other room) should be able to perform scan task. So i created asp.net 2.0 app using VS2010 and using WIA I got access to the scanner. When I debug an app from VS2010 everything works fine. Afrer clicking SCAN button I can scan documnet and save an image on server. But after deploying on IIS i am getting an authorisation error (I supose that I don't have access to the com component while running as IIS user. I thied to fix this problem, and after few days of work I tried to find other sollution. Thats how I found this article. Is there any way to scan document from web brawser (not out-of browser app)? If you can help me you will save my live:)

    Peter
  24. JoeKsays:
    Hello,
    i'm hosting the app on a server not connected to a scanner,
    but when i try to access it from another post by web that is connected to a scanner,

    i'm not able to scan ; i'm getting the error

    Détails de l’erreur de la page Web

    Agent utilisateur : Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; BRI/2)
    Horodateur : Thu, 12 May 2011 08:03:08 UTC


    Message : Unhandled Error in Silverlight Application Cette opération n'est pas prise en charge dans le contexte actuel. à MS.Internal.Error.MarshalXresultAsException(UInt32 hr, COMExceptionBehavior comExceptionBehavior)
    à MS.Internal.XcpImports.CheckHResult(UInt32 hr)
    à MS.Internal.ComAutomation.ComAutomationNative.CreateObject(String progID, IntPtr& nativeObject)
    à MS.Internal.ComAutomation.ComAutomationServices.CreateObject(String progID, ComAutomationParamWrapService paramWrapService)
    à System.Runtime.InteropServices.Automation.AutomationFactory.CreateObject(String progID)
    à PeteBrown.SilverlightScannerDemo.ScannerService.Scan()
    à PeteBrown.SilverlightScannerDemo.ScannerViewModel.Scan()
    à PeteBrown.SilverlightScannerDemo.MainPage.Scan_Click(Object sender, RoutedEventArgs e)
    à System.Windows.Controls.Primitives.ButtonBase.OnClick()
    à System.Windows.Controls.Button.OnClick()
    à System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
    à System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
    à MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
    Ligne : 1
    Caractère : 1
    Code : 0
    URI : http://192.168.11.111:4500/Silverlight.js

    pls i need a help
  25. Svensays:
    Hi guys,

    I implemented this method to convert the image on the fly:

    If imageFile.FormatID <> wiaFormatJPEG Then
    Dim ip As Object = AutomationFactory.CreateObject("WIA.ImageProcess")
    ip.Filters.Add(ip.FilterInfos("Convert").FilterID)
    ip.Filters(1).Properties("FormatID").Value = wiaFormatJPEG
    ip.Filters(1).Properties("Quality").Value = 20
    imageFile = ip.Apply(imageFile)
    End If

    However I am getting ComAutomation_BadParamCount, Argument: FilterID. Can anyone help me or at least point me in the right direction?

    Thanks
  26. Alansays:
    Very nice article, it helps me a lot on my project.

    I am just wondering if anyone knows how to scan multiple pages at once and how to convert the images to pdf document?

    Thanks
    Alan
  27. Mahendrasays:
    Hi...

    When I scan my image it will save on the local machine but when i run the xmal file it is not display into xmal Image field. How to give the source of saved scan imaged
  28. Pradeepsays:
    how to save the scanned image into database or the folder structure..


    getting this error when trying to save image

    if (imageFile != null)
    {
    imageFile.SaveFile(@"c:\myImage.jpg");

    }
    Attempted to perform an unauthorized operation.
  29. harithsays:
    i tried to this in a C# asp.net application and it did work finely in VS2010 when i deployed it in the IIS server i get error regarding some access denied to a com port
  30. Karthiksays:
    Hi Pete,

    I do see several people with "This operation is not supported in the current context" issue. Has any solution been found for this?
    I get this in the Scan() at line dynamic wiaDialog = AutomationFactory.CreateObject("WIA.CommonDialog");

    Specs:
    OS: Win7
    Environment: VS2010
    FW: 4.0

    I would be more than grateful if your could help. Awaiting your earliest reply.
    Thank you.
  31. Pete Brownsays:
    For folks getting errors, make sure you're reading the other comments here. Most are solved by installing the app and running it out of browser with elevated permissions as described in this post. Beyond that, the WIA team couldn't think of any reason why that would happen.

    For other details: it has been a while since I worked with Silverlight, so I don't have sample code for other questions here handy, sorry.

    Pete
  32. Karthiksays:
    Hi Pete,
    The whole idea of using this is to launch it from the browser. Are you saying this cannot happen? I do not wish to launch the it as a desktop application. Currently, the desktop version is working just fine.
    Can you help in anyway?

    Thank you.
  33. Petesays:
    @Karthik

    This post is all about out-of-browser elevated trust apps.

    You can create in-browser elevated trust apps, but they require group policy from an authenticated domain to set them in an organization. They are not for the public internet.

    Pete
  34. Patricio Rosasays:
    Hi Pete,


    First I had a webApp that scans documents and send them somewhere in predefined directory (resumed way).
    When i test the app, a realized that WIA don't work on as i thouht, so I moved to silverlight.
    I'm a newbie in silverlight, but i've written the code developed by you and worked as i expected. (+/-)

    My question is, how can i do it without any iterference from the user?? (My app was made to be user friendly!)


    Patricio

  35. Anandsays:
    congrats... nice article....

    Am developed one project with help of your code....... locally its work fine.... then i put site to the IIS server....
    the site Name is : testscanner...... then run from the IIS server.... the url is: "http://localhost/testscanner/" the project is work fine and able to scan the documents... like when i entered IIS Server ip address in url for example "http://10.164.2.112/testscanner/" means i got a error "COM automation is not available."

    please help to me............


    Thank you



  36. Shrikantsays:
    Hello Sir,

    I am implementing an example by :

    http://10rem.net/blog/2010/04/14/scanning-an-image-from-silverlight-4-using-wia-automation

    My problem is that I keep getting a dialog with message,

    "this action cannot be completed because the other program is busy. Choose switch-to to activate the busy program and correct the program" , with options "switch to","retry" and cancel which is disabled.

    The scanner app does scan the image. But the dialog never goes away, when I hit switch-to the start menu is launched.

    I guess this dialog comes up because the request was pending in the scanner. Can you help me with how to avoid this dialog from coming up, right now I need to kill the process via task manager to remove the dialog.

    ​Here is details of Scanner + Technology:
    Model: Canon ImageFormula DR-C130
    Technology: ASP.NET MVC C#
  37. vigneshsays:

    Error 1: Inconsistent accessibility: property type 'SilverlightApplication5.Web.BitmapSource' is less accessible than property 'SilverlightApplication5.Web.ScannerImage.Image'



    "Error 2: Inconsistent accessibility: property type 'SilverlightApplication5.Web.ImageSource' is less accessible than property 'SilverlightApplication5.Web.ScannerViewModel.ScannerImage"


    i got this above error how can i overcome this

    pls help me

Comment on this Post

Remember me