accessing webcam in web pages

2019-02-10 05:25发布

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 location.

Which will be the best way to perform this.

Methods using java, JSP, html, java script or any other methods are welcomed.

2条回答
乱世女痞
2楼-- · 2019-02-10 05:33

jQuery Webcam Plugin does the hard work for you:

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

查看更多
老娘就宠你
3楼-- · 2019-02-10 05:34

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/>
<div class="camera">
    <video id="video">Video stream not available.</video>
    <button id="startbutton">Take photo</button>
</div>
<br/>
Canvas
<br/>
<canvas id="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();

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

function takepicture() {
    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();
    }
}

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

function uploadimage(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

<select id="videoSelect"></select>
    <button id="startCameraButton">Start Camera</button>
    <br/>
    Video Tag
    <br/>
    <div class="camera">
        <video id="video">Video stream not available.</video>
        <button id="takePictureButton">Take photo</button>
    </div>
    <br/>
    Canvas
    <br/>
    <canvas id="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);
        });

function gotDevices(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);
        }
    }
}

function start() {
    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);
}



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

function handleError(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();

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

function takepicture() {
    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();
    }
}

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

function uploadimage(dataurl, filename) {
    ... upload logic here ...
}

function stopVideo() {
    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/>
            <select id="audioInputSelect"></select>
            <br/>
            audioOutputSelect
            <select id="audioOutputSelect"></select>

Script

function gotDevices(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);
        } else if (deviceInfo.kind === 'audiooutput') {
            option.text = deviceInfo.label || 'Speaker ' + (audioOutputSelect.length + 1);
            audioOutputSelect.appendChild(option);
        } else if (deviceInfo.kind === 'videoinput') {
            option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
            videoSelect.appendChild(option);
        }
    }
}

function start() {
    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);
}
查看更多
登录 后发表回答