2012-03-02 34 views
5

Estoy desarrollando una aplicación web.accediendo a la cámara web en las páginas web

En mi página de registro de invitados necesito acceder a la cámara web para tomar imágenes de invitados.

La imagen que tomo podría almacenarse en una ubicación específica.

Cuál será la mejor manera de realizar esto.

Se aceptan los métodos que usan Java, JSP, html, script java o cualquier otro método.

+0

son el servidor y el cliente de la misma máquina? – Quentin

+2

Mire en un applet Java firmado para esto. Hice esto para un bloc de firmas topaz y funcionó de maravilla, incluso pude obtener el applet firmado para instalar los controladores del panel de firmas, así que todo lo que tenían que hacer era conectarlo y visitar la página con el applet. – Zoidberg

+0

El proyecto se alojará en un servidor para que esté disponible en la LAN de una oficina, por lo que serán diferentes sistemas ... –

Respuesta

4

jQuery Plugin Webcam hace el trabajo duro para usted:

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

+0

Si esto funciona, diría que esta es la solución ideal con la menor cantidad de trabajo requerido, muy bien hecho. – Zoidberg

+0

No tengo cámara ahora (en la oficina), después de probarla con una cámara solo puedo comentar, Lo siento. –

+1

Probé esa página con una computadora portátil. En la primera ventana está mostrando la entrada de mi cámara, pero después cuando hago clic en tomar la foto, no muestra ninguna acción. –

4

Respondiendo propia pregunta, ya que hay una mejor manera usando HTML5 está disponible.

Opción 1, Acceso a la cámara por defecto del sistema

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> 

Guión

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

imagen de las cámaras

Screen shot

Opción 2, proporcionan una lista de cámaras disponibles en el sistema, y ​​permitir al usuario seleccionar la cámara.

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> 

Guión

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; 
     }); 
    } 
} 

captura de pantalla

enter image description here

Opción 3, permitir al usuario seleccionar las fuentes de vídeo y de audio y salida de audio

En la opción 2, el usuario puede elegir una cámara en particular. Además de eso, si el usuario también desea seleccionar la fuente de audio y la fuente de salida de audio, modifique el código anterior con los cambios a continuación.

HTML

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

Guión

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); 
}