Snapshot from webcam using expression encoder

2.5k views Asked by At

Been using the example i found at http://www.codeproject.com/Articles/285964/WPF-Webcam-Control to make some webcam functionality that I need. I'm mostly interested in snapshots, and i can get them to work in the example above without any issue. My main problem is that i want to be able to take a snapshot from the webcam without having a 'previewwindow' displayed for the user beforehand. Images are just saved automatically without any display or anything to the user. Below is what i have (in vb.net, but i don't mind answers in c#):

Public Shared Function TakeSnapshotReturnBytes(panelHeight As Integer, panelWidth As Integer) As Byte()
    Dim b() As Byte = Nothing
    Dim vidDevCol As IEnumerable(Of EncoderDevice) = EncoderDevices.FindDevices(EncoderDeviceType.Video)
    If vidDevCol IsNot Nothing AndAlso vidDevCol.Count > 0 AndAlso vidDevCol(0) IsNot Nothing Then
        Dim tmpJob As LiveJob = Nothing
        Dim lvDevSrc As LiveDeviceSource = Nothing
        Try
            tmpJob = New LiveJob
            Using tmpPanel As New System.Windows.Forms.Panel
                tmpPanel.Height = panelHeight
                tmpPanel.Width = panelWidth

                lvDevSrc = tmpJob.AddDeviceSource(vidDevCol(0), Nothing)
                lvDevSrc.PreviewWindow = New PreviewWindow(New HandleRef(tmpPanel, tmpPanel.Handle))
                tmpJob.ActivateSource(lvDevSrc)

                Using MS As New IO.MemoryStream()
                    Using bmp As New Bitmap(panelWidth, panelHeight)
                        tmpPanel.DrawToBitmap(bmp, New Rectangle(0, 0, bmp.Width, bmp.Height))

                        bmp.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg)
                        MS.Position = 0
                        Using br As New IO.BinaryReader(MS)
                            b = br.ReadBytes(CInt(MS.Length))
                        End Using
                    End Using
            End Using
            End Using
        Finally
            If lvDevSrc IsNot Nothing Then
                tmpJob.RemoveDeviceSource(lvDevSrc)
                lvDevSrc.Dispose()
            End If
            If tmpJob IsNot Nothing Then
                tmpJob.Dispose()
            End If
        End Try
    End If
    Return b
End Function

All I get is a grey window back though. I'm guessing i shouldn't be using the 'PreviewWindow' object, but i can't find any alternatives. Anyone else have any luck doing this?

1

There are 1 answers

1
Amir On

Change your code like this:

tmpJob.ActivateSource(lvDevSrc) 

// This delay let your camera to initialize and ready to capture image.
// Actualy we should find another safer :) way to do this but just to check if it works!
System.Threading.Thread.Sleep(5000)

Using MS As New IO.MemoryStream()

And check if this works for you. I conjecture that your webcam hadn't initialized when you captured snapshot.