Skip to content Skip to sidebar Skip to footer

Accessing Webcam In Web Pages

I am developing a web application. In my guest registration page I need to access web cam for taking images of guests. The image which I take could be able to stored in a specified

Solution 1:

Answering own question, as there is a better way using HTML5 is available.

Option 1, Accessing default camera from the system

HTML

Video Tag
<br/><divclass="camera"><videoid="video">Video stream not available.</video><buttonid="startbutton">Take photo</button></div><br/>
Canvas
<br/><canvasid="canvas"></canvas>

Script

var width = 320;
var height = 0;
var streaming = false;

navigator.mediaDevices.getUserMedia({video: true, audio: false})
        .then(function (stream) {
            video.srcObject = stream;
            video.play();
        })
        .catch(function (err) {
            console.log("An error occured! " + err);
        });

video.addEventListener('canplay', function (ev) {
    if (!streaming) {
        height = video.videoHeight / (video.videoWidth / width);
        video.setAttribute('width', width);
        video.setAttribute('height', height);
        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);

        streaming = true;
    }
}, false);

startbutton.addEventListener('click', function (ev) {
    takepicture();
    ev.preventDefault();
}, false);

clearphoto();

functionclearphoto() {
    var context = canvas.getContext('2d');
    context.fillStyle = "#AAA";
    context.fillRect(0, 0, canvas.width, canvas.height);
}

functiontakepicture() {
    var context = canvas.getContext('2d');
    if (width && height) {
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);

        var dataURL = canvas.toDataURL("image/jpeg", 0.95);
        if (dataURL && dataURL != "data:,") {
            var fileName = generateImageName();
            uploadimage(dataURL, fileName);
        } else {
            alert("Image not available");
        }
    } else {
        clearphoto();
    }
}

functiongenerateImageName() {
    ... generate image name logic here ...
    return imageName;
}

functionuploadimage(dataurl, filename) {
    ... upload logic here ...
}

Screen shot

Screen shot

Option 2, Provide a list of available cameras in the system, and let user select the camera.

HTML

<selectid="videoSelect"></select><buttonid="startCameraButton">Start Camera</button><br/>
    Video Tag
    <br/><divclass="camera"><videoid="video">Video stream not available.</video><buttonid="takePictureButton">Take photo</button></div><br/>
    Canvas
    <br/><canvasid="canvas"></canvas>

Script

var width = 320;
var height = 0;
var streaming = false;
var localstream = null;

startCameraButton.onclick = start;
takePictureButton.onclick = takepicture;

navigator.mediaDevices.enumerateDevices()
        .then(gotDevices)
        .catch(function (err) {
            console.log("An error occured while getting device list! " + err);
        });

functiongotDevices(deviceInfos) {
    while (videoSelect.firstChild) {
        videoSelect.removeChild(videoSelect.firstChild);
    }

    for (var i = 0; i !== deviceInfos.length; ++i) {
        var deviceInfo = deviceInfos[i];
        var option = document.createElement('option');
        option.value = deviceInfo.deviceId;
        if (deviceInfo.kind === 'videoinput') {
            option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
            videoSelect.appendChild(option);
        }
    }
}

functionstart() {
    stopVideo();
    clearphoto();
    var videoSource = videoSelect.value;
    var constraints = {
        audio: false,
        video: {deviceId: videoSource ? {exact: videoSource} : undefined}
    };
    navigator.mediaDevices.getUserMedia(constraints).
            then(gotStream).then(gotDevices).catch(handleError);
}



functiongotStream(stream) {
    localstream = stream;
    video.srcObject = stream;
    video.play();
    // Refresh button list in case labels have become availablereturn navigator.mediaDevices.enumerateDevices();
}

functionhandleError(error) {
    console.log('navigator.getUserMedia error: ', error);
}

video.addEventListener('canplay', function (ev) {
    if (!streaming) {
        height = video.videoHeight / (video.videoWidth / width);
        video.setAttribute('width', width);
        video.setAttribute('height', height);
        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);

        streaming = true;
    }
}, false);

clearphoto();

functionclearphoto() {
    var context = canvas.getContext('2d');
    context.fillStyle = "#AAA";
    context.fillRect(0, 0, canvas.width, canvas.height);
}

functiontakepicture() {
    var context = canvas.getContext('2d');
    if (width && height) {
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);

        var dataURL = canvas.toDataURL("image/jpeg", 0.95);
        if (dataURL && dataURL != "data:,") {
            var fileName = generateImageName();
            fileName = fileName + ".txt"uploadimage(dataURL, fileName);
        } else {
            console.log("Image not available");
        }
    } else {
        clearphoto();
    }
}

    functiongenerateImageName() {
    ... generate image name logic here ...
    return imageName;
}

functionuploadimage(dataurl, filename) {
    ... upload logic here ...
}

functionstopVideo() {
    if (localstream) {
        localstream.getTracks().forEach(function (track) {
            track.stop();
            localstream = null;
        });
    }
}

Screen Shot

enter image description here

Option 3, let user select audio and video sources and audio output

In option 2, user can select any particular camera. On top of that if user want to select audio source and audio output source also, modify the above code with below changes.

HTML

            audioInputSelect
            <br/><selectid="audioInputSelect"></select><br/>
            audioOutputSelect
            <selectid="audioOutputSelect"></select>

Script

functiongotDevices(deviceInfos) {
    while (videoSelect.firstChild) {
        videoSelect.removeChild(videoSelect.firstChild);
    }

    for (var i = 0; i !== deviceInfos.length; ++i) {
        var deviceInfo = deviceInfos[i];
        var option = document.createElement('option');
        option.value = deviceInfo.deviceId;
        if (deviceInfo.kind === 'audioinput') {
            option.text = deviceInfo.label || 'Microphone ' + (audioInputSelect.length + 1);
            audioInputSelect.appendChild(option);
        } elseif (deviceInfo.kind === 'audiooutput') {
            option.text = deviceInfo.label || 'Speaker ' + (audioOutputSelect.length + 1);
            audioOutputSelect.appendChild(option);
        } elseif (deviceInfo.kind === 'videoinput') {
            option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
            videoSelect.appendChild(option);
        }
    }
}

functionstart() {
    stopVideo();
    clearphoto();
    var audioSource = audioInputSelect.value;
    var videoSource = videoSelect.value;
    var constraints = {
      audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
        video: {deviceId: videoSource ? {exact: videoSource} : undefined}
    };
    navigator.mediaDevices.getUserMedia(constraints).
            then(gotStream).then(gotDevices).catch(handleError);
}

Solution 2:

jQuery Webcam Plugin does the hard work for you:

http://www.xarg.org/project/jquery-webcam-plugin/

Post a Comment for "Accessing Webcam In Web Pages"