Dailycode.info

Short solution for short problems

Using WIA 2.0 to take picture

I have a webcam connected via USB to my pc. I needed to take a picture and do some calculations to it.

As I started to use the WIA library I noticed that it supported VB.Net better then c#. Some things where not possible in c#. I create an interface, ICamera and a class Camera that implemented this interface. The Camera is written in VB.Net because of limitations in c#.

For now the class exposes 1 function: TakePicture. This funtion takes a picture, returns an System.Drawing.Image and cleans up reasources. Here is the class that does the work:

Imports System.Drawing
Imports NSP.Win.Interfaces.IO
Imports WIA
Imports System.IO
...
 
Public Function TakePicture() As System.Drawing.Image Implements ICamera.TakePicture
 
        Dim returnImg As Image = Nothing
        Dim DefaultDevice As Device
        Dim Dialog1 As New WIA.CommonDialog
        DefaultDevice = Dialog1.ShowSelectDevice 'Does NOT show dialog. Merely retrieves device. 
        Dim total As Integer
        total = DefaultDevice.Items.Count
 
        Dim Item As WIA.Item = DefaultDevice.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture)
        Dim Img As WIA.ImageFile = Item.Transfer 'because this item is an image. 
 
        'Dim Img As WIA.ImageFile = DefaultDevice.Items(total).Transfer() 'Whereas ShowTransfer() shows the progress bar. 
        If File.Exists("MyImage.Tif") Then
            File.Delete("MyImage.Tif")
        End If
        Img.SaveFile("MyImage.Tif")
        returnImg = Image.FromFile("MyImage.Tif")
 
 
        Dim x As Short
        ' Remove all items from the current device
        For Each WIAItm In DefaultDevice.Items
            ' Run through each item and remove
            For x = 1 To DefaultDevice.Items.Count
                Try
                    ' Remove the item
                    DefaultDevice.Items.Remove(x)
                    ' Exit the loop
                    Exit For
                Catch exp As Exception
                End Try
            Next
        Next
        Return returnImg
    End Function
End Class

 

I'm starting to investigate the properties of the WIA device, so I can set the brithgness, resolution etc and expose them via an interface. Maybe I will post this later on.

If you are wondering what different in c#, for example, less or practically no information, also, the dialog.showselectdevice cannot be addressed in c# without parameters, and it will always show the GUI.