In getUserMedia article I explained how we can retrieve webcam video using JavaScript. Developers started applying different techniques to retrieve a single frame out of the stream which would result in a captured image. But non of these techniques to capture a image was standard. Therefore a new image capture API was introduced to capture images using JavaScript.
ImageCapture API
ImageCapture class is the heart of the API. It takes an video track and extracts a image out of it. Let’s see an example of how its done:
View Demo
var video_audio_properties = {video: true};
video_audio_properties = {video: {mandatory: {minWidth: 300, minHeight: 300, minFrameRate: 30}, optional: [{ minFrameRate: 60 }]}, audio: true};
function onSuccess(stream)
{
var videoDevice = stream.getVideoTracks()[0];
if(window.ImageCapture)
{
var pictureDevice = new ImageCapture(videoDevice);
pictureDevice.onphoto = showImage;
pictureDevice.onphotoerror = photoError;
//take the photo
pictureDevice.takePhoto();
}
else
{
alert("Image Capture API is not supported");
}
}
//a blob of the caotured image is passed to the success callback
function showImage(blobeven)
{
//retrieve the Data URI of the image
document.getElementById("captured_image").src = URL.createObjectURL(blobevent.data);
}
function photoError()
{
console.log('failure to take photo');
}
function onError(error)
{
console.log("Video capture error: ", error.code);
}
if(navigator.getUserMedia != null)
{
navigator.getUserMedia(video_audio_properties, onSuccess, onError);
}
else
{
alert("microphone and webcam API not supported");
}
ImageCapture provides a lot of other customisation that can be applied to the retrieved image. More on it here.
Leave a Reply