Taking cropped webcam photos with live digital zoom preview
Taking a photo from a cropped webcam video can be useful for taking square identification photos, or any other situation where you’d like to crop out most of the background without needing the subject to get super close to the web camera.
My example for Chrome:Digital Webcamera Zoom shows how to provide the user with an approximate live preview of what will be cropped from the image using an HTML5 canvas overlay. It also demonstrates initializing the camera with Full-HD resolution (1920x1080), progressively falling back to lower resolutions if needed.
One thing to note is that behind the scenes, a full-resolution photo is being taken, even though the video and photo previews are smaller. The video and canvas elements remain in full resolution, while CSS styling resizes the HTML element to appear smaller. You can then scale and crop the final image using a high-quality server side library such as Microsoft .NET Core Image Processing
This uses the ImageCapture Web API as demonstrated in Google Chrome’s Github to grab a high-quality still frame from the live video. Not all browsers support this feature but support is growing.
Code highlights
Drawing the scaled and cropped photo
The photo is captured from the video feed using Chrome’s ImageCapture API. Then you can then draw the image onto a canvas to scale and crop it. Some trial and error was needed to get an algorithm that looked good at every resolution. Note that Full-HD and HD webcams have a wider aspect ratio than VGA webcams.
Drawing the translucent crop preview
Changing the zoom slider draws an HTML5 canvas overlay on top of the video preview. The canvas is positioned using position:absolute over the HTML5 video element in CSS.