MediaStream Image Capture API
TheMediaStream Image Capture API is an API for capturing images or videos from a photographic device. In addition to capturing data, it also allows you to retrieve information about device capabilities such as image size, red-eye reduction and whether or not there is a flash and what they are currently set to. Conversely, the API allows the capabilities to be configured within the constraints what the device allows.
In this article
MediaStream image capture concepts and usage
The process of retrieving an image or video stream happens as described below. The example code is adapted fromChrome's Image Capture examples.
First, get a reference to a device by callingMediaDevices.getUserMedia()
. The example below says give me whatever video device is available, though thegetUserMedia()
method allows more specific capabilities to be requested. This method returns aPromise
that resolves with aMediaStream
object.
navigator.mediaDevices.getUserMedia({ video: true }).then((mediaStream) => { // Do something with the stream.});
Next, isolate the visual part of the media stream. Do this by callingMediaStream.getVideoTracks()
. This returns an array ofMediaStreamTrack
objects. The code below assumes that the first item in theMediaStreamTrack
array is the one to use. You can use the properties of theMediaStreamTrack
objects to select the one you need.
const track = mediaStream.getVideoTracks()[0];
At this point, you might want to configure the device capabilities before capturing an image. You can do this by callingapplyConstraints()
on the track object before doing anything else.
let zoom = document.querySelector("#zoom");const capabilities = track.getCapabilities();// Check whether zoom is supported or not.if (!capabilities.zoom) { return;}track.applyConstraints({ advanced: [{ zoom: zoom.value }] });
Finally, pass theMediaStreamTrack
object to theImageCapture()
constructor. Though aMediaStream
holds several types of tracks and provides multiple methods for retrieving them, the ImageCapture constructor will throw aDOMException
of typeNotSupportedError
ifMediaStreamTrack.kind
is not"video"
.
let imageCapture = new ImageCapture(track);
Interfaces
ImageCapture
An interface for capturing images from a photographic device referenced through a valid
MediaStreamTrack
.
Specifications
Specification |
---|
MediaStream Image Capture> # imagecaptureapi> |
Browser compatibility
Loading…