Search code examples
vb.netzoomingwebcam

Can I digitally zoom my webcam feed in VB?


I'm kind of picking a project up where somebody else left off years ago here. I'm using Visual Studio 2012, and the application is a win forms written in VB. I have a window that displays my webcam's feed and snaps pictures, but I need to add the ability to zoom (digitally, as the web cam does not have optical zoom.)

Currently, the project uses DirectShowLib. The control on the form that displays the video is a user control (written god knows how long ago) that implements ISampleGrabberCb, but I honestly know next to nothing about a/v stuff, and this project needs the update STAT.


Solution

  • Yes it's possible.

    Your webcam will just be producing bitmap frames. You can then draw these onto any surface you like. The easiest way to do this is with the gdi functions.

    Here's a brief outline of what it should look like

    Dim mBitmap As Bitmap
    Dim mZoomRect As Rectangle = New Rectangle(100, 100, 100, 100)
    
    Public Sub OnFrameReceived(frame As Bitmap)
        mBitmap = CType(frame, Bitmap)
        'Tell the form to redraw itself.
        Me.Invalidate()
    End Sub
    
    Private Sub MyPaintHandler(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        e.Graphics.DrawImage(mBitmap, Me.ClientRectangle, mZoomRect, GraphicsUnit.Pixel)
    End Sub
    

    You have to be a bit careful with synchronization as your frames are arriving at a different time to your image being painted. And you also need to take care about when the bitmaps are disposed. When i do this I clone the bitmap in the OnFrameReceived handler so that I'm in charge of its lifecycle.

    GDI is pretty slow though. I now use OpenTK for handling this in my applications.