I am trying to capture image from webcam into a canvas and I would like to store this image data as an pixel array. How can I store it, please?
this is how I am drawing the picture from webcam to a context:
context = canvas.getcontext('2d');
captureButton.addEventListerner('click', ()=> {
context.drawImage(player, 0, 0, canvas.width. canvas.height);}
player is defined in html as <video id='player' controls autoplay></video>
best regards
This is something I've already done in my library jsia, so I'll expand it out for you here:
This doesn't work on Stack Exchange because of security restrictions, but you can see it working at https://mellen.github.io/jsiaExamples/barcodeReader
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var vid = document.getElementById('vid');
function setupVideoCallback(videoElement, callbackCapture, callbackError, timeBetweenFrames)
{
var localMediaStream = null;
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia );
var um = navigator.mediaDevices.getUserMedia({video: true}).then(handleVid).catch(vidErr);
if(!um)
{
um = navigator.getUserMedia({video: true}, handleVid, vidErr);
}
function handleVid(stream)
{
videoElement.srcObject = stream;
localMediaStream = stream;
}
function vidErr(e)
{
callbackError(e)
}
function capture()
{
if(localMediaStream)
{
callbackCapture();
}
}
setInterval(capture, timeBetweenFrames);
}
function drawVideoOnCanvas()
{
canvas.width = vid.clientWidth;
canvas.height = vid.clientHeight;
ctx.drawImage(vid, 0, 0);
}
setupVideoCallback(vid, drawVideoOnCanvas, e => console.log(e), 10);
<canvas id="canvas"></canvas>
<video autoplay style="visibility:hidden" id="vid"></video>
Related
Is there a way to capture a higher resolution image than the actual width of my onscreen video element which is showing my webcam image that I intend to capture?
Currently, I have set the width in getUserMedia to 1280, but my element is constrained to 640px. I'd like to still be storing images of 1280px wide so that I'm getting higher quality images.
Code:
<div id="video-container">
<h3 id="webcam-title">Add Photos</h3>
<video id="video" autoplay playsinline></video>
<select id="videoSource"></select>
<div id="take-photo-button" onclick="takeSnapshot();">TAKE PHOTO <div class="overlay"></div></div>
<canvas id="myCanvas" style="display:none;"></canvas>
<div id="snapshot-container"></div>
<div id="approval-form-submit">SAVE ORDER</div>
</div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script>
$(function() {
var video = document.querySelector('video');
var videoSelect = document.querySelector('select#videoSource');
var initialized = false;
//Obtain media object from any browser
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
var video_height, snapshot_height;
//var video_width = 1280;
var video_width = 640;
var container_width = 800;
var snapshot_margin = 10;
var snapshot_width = (container_width - snapshot_margin*6)/3;
//var snapshot_width = 1280;
function fillSelectWithDevices(deviceInfos) {
var value = videoSelect.value;
$(videoSelect).empty();
for (let i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
if (deviceInfo.kind === 'videoinput') {
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
option.text = deviceInfo.label || `camera ${videoSelect.length + 1}`;
videoSelect.appendChild(option);
if(!initialized && deviceInfo.label==='Back Camera'){
value = deviceInfo.deviceId;
initialized = true;
}
}
if (Array.prototype.slice.call(videoSelect.childNodes).some(n => n.value === value)) {
videoSelect.value = value;
}
}
}
function gotStream(stream) {
window.stream = stream; // make stream available to console
video.srcObject = stream;
video.addEventListener('canplay', function(ev){
video_height = video.videoHeight * (video_width/video.videoWidth);
snapshot_height = video.videoHeight * (snapshot_width/video.videoWidth);
initCanvas();
// Firefox currently has a bug where the height can't be read from
// the video, so we will make assumptions if this happens.
if (isNaN(video_height)) {
video_height = video_width * (3/4);
console.log("Can't read video height. Assuming 4:3 aspect ratio");
}
//video_width=640;
//video_height=480;
video.setAttribute('width', video_width);
video.setAttribute('height', video_height);
canvas.setAttribute('width', video_width);
canvas.setAttribute('height', video_height);
}, false);
return navigator.mediaDevices.enumerateDevices();
}
function handleError(error) {
console.log('navigator.getUserMedia error: ', error);
}
function start() {
if (window.stream) {
window.stream.getTracks().forEach(track => {
track.stop();
});
}
var videoSource = videoSelect.value;
var constraints = {
video: {deviceId: videoSource ? {exact: videoSource} : undefined,
facingMode: "environment",
width:1280},
audio: false
};
navigator.mediaDevices.getUserMedia(constraints).then(gotStream).then(fillSelectWithDevices).catch(handleError);
}
videoSelect.onchange = start;
start();
var canvas, ctx, container;
function initCanvas() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext('2d');
container = document.getElementById("snapshot-container");
//Reconstitute snapshots from form URI after failed submit
var image_list_field = $('#image-list-field'),
URI_array = image_list_field.val().split(','),
dataURI;
for(var i = 0;i<URI_array.length;i++){
if(URI_array[i]){
dataURI = "data:image/png;base64,"+URI_array[i];
displaySnapshot(dataURI);
}
}
}
// Capture a photo by fetching the current contents of the video
// and drawing it into a canvas, then converting that to a PNG
// format data URL. By drawing it on an offscreen canvas and then
// drawing that to the screen, we can change its size and/or apply
// other changes before drawing it.
takeSnapshot = function() {
alert (video_width + " " + video_height);
ctx.drawImage(video, 0, 0, video_width, video_height);
var data = canvas.toDataURL('image/png');
displaySnapshot(data);
}
function displaySnapshot(data){
var photo = document.createElement('img'),
snapshot_div = document.createElement('div'),
delete_text = document.createElement('p');
photo.setAttribute('src', data);
$(photo).css({"width":snapshot_width+"px"});
$(photo).addClass("snapshot-img");
$(snapshot_div).css({"width":snapshot_width+"px","height":snapshot_height+25+"px"});
$(delete_text).text("Delete Photo");
$(snapshot_div).append(photo).append(delete_text);
$(delete_text).on('click',function(){$(this).closest('div').remove()})
container.append(snapshot_div);
}
$('#approval-form-submit').on('click',function(e){
var form = $('#approval-form'),
image_list_field = $('#image-list-field'),
imageURI;
image_list_field.val("");
$('.snapshot-img').each(function(i, d){
imageURI = d.src.split(',')[1]+',';
image_list_field.val(image_list_field.val()+imageURI);
});
form.submit();
})
I'm doing one project using html and java-script but i'm new to java-script but i know little bit about js functionality..my project is based on Webcam and Captured images from my webcam i have completed upto Webcam and i takes pictures from my webcam and Now im problem is i want to save my captured images using captured button Id i tried but i cant get exact result.if any one knows please help me..
Here is my coding:'cam-video.html'
<div class="container" id="videophoto">
<div class="row">
<div class="col-sm-6 col-md-6">
<div id="container">
<video id="videoel" width="400" height="300" preload="auto" loop playsinline autoplay>
</video>
<canvas id="overlay" width="400" height="300"></canvas>
</div>
<button id="capture" class="pic">Capture</button><br />
<!--<img src="examples/media/audrey.jpg" />-->
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<img src="" id="photo" alt="photo">
Here is my javascript:'mine.js'
<script>
var vid = document.getElementById('videoel');
var vid_width = vid.width;
var vid_height = vid.height;
var overlay = document.getElementById('overlay');
var overlayCC = overlay.getContext('2d');
/*********** Setup of video/webcam and checking for webGL support *********/
function enablestart() {
var starttbutton = document.getElementById('starttbutton');
starttbutton.value = "start";
starttbutton.disabled = null;
}
var insertAltVideo = function(video) {
// insert alternate video if getUserMedia not available
if (supports_video()) {
if (supports_webm_video()) {
video.src = "./media/cap12_edit.webm";
} else if (supports_h264_baseline_video()) {
video.src = "./media/cap12_edit.mp4";
} else {
return false;
}
return true;
} else return false;
}
function adjustVideoProportions() {
// resize overlay and video if proportions of video are not 4:3
// keep same height, just change width
var proportion = vid.videoWidth/vid.videoHeight;
vid_width = Math.round(vid_height * proportion);
vid.width = vid_width;
overlay.width = vid_width;
}
function gumSuccess( stream ) {
// add camera stream if getUserMedia succeeded
if ("srcObject" in vid) {
vid.srcObject = stream;
} else {
vid.src = (window.URL && window.URL.createObjectURL(stream));
}
vid.onloadedmetadata = function() {
adjustVideoProportions();
vid.play();
}
vid.onresize = function() {
adjustVideoProportions();
if (trackingStarted) {
ctrack.stop();
ctrack.reset();
ctrack.start(vid);
}
}
}
function gumFail() {
// fall back to video if getUserMedia failed
insertAltVideo(vid);
document.getElementById('gum').className = "hide";
document.getElementById('nogum').className = "nohide";
alert("There was some problem trying to fetch video from your webcam, using a fallback video instead.");
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.msURL || window.mozURL;
// set up video
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({video : true}).then(gumSuccess).catch(gumFail);
} else if (navigator.getUserMedia) {
navigator.getUserMedia({video : true}, gumSuccess, gumFail);
} else {
insertAltVideo(vid);
document.getElementById('gum').className = "hide";
document.getElementById('nogum').className = "nohide";
alert("Your browser does not seem to support getUserMedia, using a fallback video instead.");
}
vid.addEventListener('canplay', enablestart, false);
/*********** Code for face tracking *********/
var ctrack = new clm.tracker();
ctrack.init();
var trackingStarted = false;
function startVideo() {
// start video
vid.play();
// start tracking
ctrack.start(vid);
// var time=setTimeout("alert('Two Faces Not Allowed')",3500);
trackingStarted = true;
// start loop to draw face
drawLoop();
}
function drawLoop() {
requestAnimFrame(drawLoop);
overlayCC.clearRect(0, 0, vid_width, vid_height);
//psrElement.innerHTML = "score :" + ctrack.getScore().toFixed(4);
if (ctrack.getCurrentPosition()) {
ctrack.draw(overlay);
document.getElementById('photo').setAttribute('src', data);
}
}
/*********** Code for stats **********/
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
document.getElementById('container').appendChild( stats.domElement );
// update stats on every iteration
document.addEventListener('clmtrackrIteration', function(event) {
stats.update();
}, false);
</script>
<script type="text/javascript">
(function() {
var streaming = false,
video = document.querySelector('#video'),
canvas = document.querySelector('#canvas'),
buttoncontent = document.querySelector('#buttoncontent'),
photo = document.querySelector('#photo'),
startbutton = document.querySelector('#startbutton'),
width = 320,
height = 0;
navigator.getMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia({
video: true,
audio: false
},
function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
}
video.play();
},
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);
function takepicture(data_uri) {
video.style.display = "none";
canvas.style.display = "block";
startbutton.innerText= "RETAKE";
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(videoel, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
var data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
document.getElementById("two").value = data;
document.myForm.sub();
document.getElementById('capture').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
document.myForm.sub();
}
startbutton.addEventListener('click', function(ev) {
if(startbutton.innerText==="CAPTURE")
{
takepicture();
}
else
{
video.style.display = "block";
canvas.style.display = "none";
startbutton.innerText= "CAPTURE";
}
ev.preventDefault();
}, false);
})();
</script>
<script>
$(document).ready(function(){
$("#startbutton").click(function(){
$("#choosephoto").hide(1000);
});
});
</script>
Here is the code that i have tried how to save my captured images from webcam..
function takepicture(data_uri) {
video.style.display = "none";
canvas.style.display = "block";
startbutton.innerText= "RETAKE";
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(videoel, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
var data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
document.getElementById("two").value = data;
document.myForm.sub();
document.getElementById('capture').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
document.myForm.sub();
}
//$
the above part of code is i have tried.Can anyone help Me please.
I'm capturing photo via webcam on a web application, which would display the captured photo on screen, then send it to servlet so that I can save it directly to a path in my computer.
My problem now is I don't know how to post the photo to servlet. I googled and found some code that can upload a user-chosen file to servlet, but I need my webcam photo to be the form input without letting user choose a file to upload. I have the id of the photo.
Here's what I found:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload: <input type="file" name="file" size="60" /><br /><br />
<input type="submit" value="Upload" />
</form>
This code integrates well with my code and everything can run, but I don't want to upload a file, I want to set the captured image as my form input so the user just have to click "submit" after seeing the image.
Code that displays the captured photo:
<div class="output"><img id="photo" alt="The image preview will appear in this box."></div>
The captured photo is rendered and displayed here as a PNG image. How do I make it the form input?
JavaScript:
(function() {
var width = 320;
var height = 0;
var streaming = false;
var video = null;
var canvas = null;
var photo = null;
var startbutton = null;
function startup() {
video = document.getElementById('video');
canvas = document.getElementById('canvas');
photo = document.getElementById('photo');
var confirmPhoto = document.getElementById('photo');
startbutton = document.getElementById('startbutton');
navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia(
{
video: true,
audio: false
},
function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
}
video.play();
},
function(err) {
console.log("An error occured! " + err);
}
);
video.addEventListener('canplay', function(ev){
if (!streaming) {
height = video.videoHeight / (video.videoWidth/width);
if (isNaN(height)) {
height = width / (4/3);
}
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);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
}
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
} else {
clearphoto();
}
}
window.addEventListener('load', startup, false);})();
Please help! Thank you!!
I'm trying to create a streaming video for a project, I am creating in node.js including html, and I can not finish by this error
Uncaught TypeError: Can not read property 'getContext' of null
then I need to fix that problem, but I can not because I sought solutions and this type of error, but none works for me up to work only issue
I had to comment on these lines:
var context = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;
context.width = canvas.width;
context.height = canvas.height
Here the codes of my proyect:
Emitir Video
<canvas style = "display:none;" id "preview" width='1280' height='720'></canvas>
<div id = "logger"></div>
<script type="text/javascript">
var canvas = document.getElementById("preview");
var context = canvas.getContext("2d"); // This is the line that generates the error
canvas.width = 800;
canvas.height = 600;
context.width = canvas.width;
context.height = canvas.height;
var video = document.getElementById("video");
var socket = io();
function logger(msg)
{
$("#logger").text(msg);
}
function loadCam(stream)
{
video.src = window.URL.createObjectURL(stream);
logger('Camara cargada correctamente [OK]');
}
function loadFail()
{
logger('Camara no conectada, Favor Conectela');
}
function viewVideo(video,context)
{
context.drawImage(video,0,0,context.width,context.height);
socket.emit('stream',canvas.toDataURL('image/webp'));
}
$(function(){
navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msgGetUserMedia);
if (navigator.getUserMedia)
{
navigator.getUserMedia({video: true}, loadCam, loadFail);
}
//1000 = 1 Seg.
setInterval(function(){
viewVideo(video,context);
},70);
});
</script>
</body>
</html>
Thanks i will apreciate helps.
You need to change id "preview" to id="preview", then you can move on to whatever the next error will be :)
I have a page which uses the HTML5 getUserMedia functionality to capture an image from the user's webcam. I am having serious inconsistencies in the scaling of the captured image when it is rendered to the canvas. Only the top corner of the image is actually rendered, as if rather than capturing the video element, it is slicing a piece from the underlying stream. Oddly enough, when I go to most other sites using this technology, I do not have this problem. I am running Chrome 29.0.1547.76 m on Windows 7, running on a 2011 MacBook Pro.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var openCameraButton;
var takePictureButton;
var mediaStream;
var video;
var canvas;
var context;
navigator.getMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
function onLoad(){
video = document.querySelector('video');
canvas = document.querySelector('canvas');
context = canvas.getContext('2d');
context.imageSmoothingEnabled = true;
context.webkitImageSmoothingEnabled = true;
context.mozImageSmoothingEnabled = true;
};
function openCamera(){
navigator.getMedia(
{ video:true, audio: false },
function(localMediaStream){
mediaStream = localMediaStream;
video.src=window.URL.createObjectURL(localMediaStream);
},
function(err){
alert('Unable to support live capture.');
}
);
}
function takePicture(){
var w = video.videoWidth;
var h = video.videoHeight;
context.drawImage(video,0,0,w,h);
canvas.style.display='block';
video.style.display='none';
}
</script>
</head>
<body onload="onLoad();">
<div>
<video autoplay style="width:640px; height:480px;"></video>
<canvas style="width:640px; height:480px; display:none;"></canvas>
</div>
<div>
<button id="openCameraButton" type="button" onclick="openCamera();" >Open Camera</button>
<button id="takePictureButton" type="button" onclick="takePicture();" >Take Picture</button>
</div>
</body>
</html>
Any ideas?
please try this:
function takePicture(){
var w = video.videoWidth;
var h = video.videoHeight;
canvas.width = w;
canvas.height = h;
context.drawImage(video,0,0,w,h);
canvas.style.display='block';
video.style.display='none';
}