I´m traying to get my webcam, take a photo and upload to my filesystem. My problem it´s that my form data it´s empty and i don´t know where it´s my problem. Attach my code and my blade.
this it´s my html:
<div class="form-group">
<label for="videoSelect">Camera</label>
<div class="camera">
<select id="videoSelect" class="custom-select"></select>
<button id="startCameraButton" class="btn btn-success">Start Camera</button>
<video id="video">Video stream not available.</video>
<button id="takePictureButton" class="btn btn-info d-none">Take photo</button>
</div>
<canvas class="d-none" id="canvas" name="fileName"></canvas>
</div>
And this it´s my javascript:
<script>
document.getElementById("editProfile").addEventListener("click", function(event){
event.preventDefault()
});
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() {
takePictureButton.classList.remove("d-none")
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() {
canvas.classList.remove("d-none")
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;
uploadimage(dataURL, fileName);
} else {
console.log("Image not available");
}
} else {
clearphoto();
}
}
function generateImageName() {
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+'_'+time;
let name = document.getElementById("inputName").value;
return name+"_"+dateTime+ ".jpg";
}
function uploadimage(dataurl, filename) {
let image = new Image();
image.src = dataurl;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
console.log('¡Éxito!', xhr.response);
}else{
console.log('Error en la petición!');
}
}
xhr.open('POST', "{{ route('patients.profileImage') }}");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-CSRF-Token", "{{ csrf_token() }}");
var formData = new FormData();
formData.append("image", image.src);
formData.append("fileName", filename);
//xhr.send(formData);
}
function stopVideo() {
if (localstream) {
localstream.getTracks().forEach(function (track) {
track.stop();
localstream = null;
});
}
}
</script>
My controller:
function profileImage(Request $request)
{
$img = $request->get('image');
$imgTran1 = str_replace('data:image/jpg;base64,', '', $img);
$imgTran2 = str_replace(' ', '+', $imgTran1);
$data = base64_decode($imgTran2);
\Storage::disk('public')->move($img, $data);
}
My problem it´s that form data in javascript it´s empty, i don´t know why... I don´t see my error.
Thans for read me and sorry for my bad english
Related
I'm trying to pass a jpg that I have stored in a table as a blob to the following javascript code:
class ImageLoader {
constructor(imageWidth, imageHeight) {
this.canvas = document.createElement('canvas');
this.canvas.width = imageWidth;
this.canvas.height = imageHeight;
this.ctx = this.canvas.getContext('2d');
}
async getImageData(url) {
await this.loadImageAsync(url);
const imageData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height);
return imageData;
}
loadImageAsync(url) {
return new Promise((resolve, reject) => {
this.loadImageCb(url, () => {
resolve();
});
});
}
loadImageCb(url, cb) {
loadImage(
url,
img => {
if (img.type === 'error') {
throw `Could not load image: ${url}`;
} else {
// load image data onto input canvas
this.ctx.drawImage(img, 0, 0)
//console.log(`image was loaded`);
window.setTimeout(() => { cb(); }, 0);
}
},
{
maxWidth: this.canvas.width,
maxHeight: this.canvas.height,
cover: true,
crop: true,
canvas: true,
crossOrigin: 'Anonymous'
}
);
}
}
I've tried get APEX_UTIL.GET_BLOB_FILE_SRC, but then the javascript code throws the error "Could not load image".
I then to use the following procedure:
create or replace PROCEDURE get_file (p_file_name IN VARCHAR2) IS
l_blob_content UPLOADED_IMAGES.blob_content%TYPE;
l_mime_type UPLOADED_IMAGES.mime_type%TYPE;
BEGIN
SELECT blob_content,
mime_type
INTO l_blob_content,
l_mime_type
FROM UPLOADED_IMAGES
WHERE filename = p_file_name;
sys.HTP.init;
sys.OWA_UTIL.mime_header(l_mime_type, FALSE);
sys.HTP.p('Content-Length: ' || DBMS_LOB.getlength(l_blob_content));
sys.HTP.p('Content-Disposition: filename="' || p_file_name || '"');
sys.OWA_UTIL.http_header_close;
sys.WPG_DOCLOAD.download_file(l_blob_content);
apex_application.stop_apex_engine;
EXCEPTION
WHEN apex_application.e_stop_apex_engine
THEN RAISE;
WHEN OTHERS THEN
HTP.p('Whoops');
END;
Still the same error "Could not load image" and a new error "Whoops Status:204 No Content X-Content-Type-Options:nosniff X-Xss-Protection:1; mode=block Referrer-Policy:strict-origin Cache-Control:no-store Pragma:no-cache Expires:Sun, 27 Jul 1997 13:00:00 GMT X-Frame-Options:SAMEORIGIN".
So I'm not sure what I'm doing wrong or how to better go about doing this right.
Update:
I've now tried "blob2clobbase64", but that doesn't seem to anything:
declare
l_image_clob clob;
l_image_blob blob;
begin
select BLOB_CONTENT
into l_image_blob
from UPLOADED_IMAGES
where FILENAME = :P1_IMAGES;
l_image_clob := apex_web_service.blob2clobbase64(
p_blob => l_image_blob
);
apex_json.open_object;
apex_json.write('imageBase64', l_image_clob );
apex_json.close_object;
end;
The code I'm using for image loading:
const imageSize = 224;
const imageBLOB = new Image();
// Load image.
apex.server.process(
"get_file",
{},
{
success: function(data) {
imageBLOB.src = 'data:image/jpeg;base64,' + data.imageBase64;
const imageLoader = new ImageLoader(imageSize, imageSize);
const imageData = await imageLoader.getImageData(imageBLOB);
}
}
);
I got it to work. I ended up using the "blob2clobbase64" process and instead of using the ImageLoader class and instead used getImageData from the canvas. The PL/SQL is the same but the JavaScript is different:
const imageSize = 224;
var newImageDate;
function returnImageData(imageData){
return newImageDate = imageData;
}
async function runImageExample(){
apex.server.process(
"get_image", {}, {
success: async function(data) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var imageBLOB = new Image();
imageBLOB.onload = function() {
imageBLOB.crossOrigin = "Anonymous";
ctx.drawImage(imageBLOB, 0, 0, imageSize, imageSize);
var imgData = ctx.getImageData(0, 0, imageSize, imageSize);
returnImageData(imgData.data);
};
imageBLOB.src = 'data:image/jpeg;base64,' + data.photoBase64;
}
}
);
}
I need to modify existing code with new requirement:
Image dimensions has to be validated before upload from browser.
If height or width of image is less than 500 px it has to be increased to 500px.
Here is the code that currently used in our app to upload images.
var fileInputElem = document.getElementById('P3_FILE');
var fileIndex = 0;
var deferredObject = $.Deferred();
var s$=apex.widget.waitPopup;
// builds a js array from long string
function clob2Array(clob, size, array) {
loopCount = Math.floor(clob.length / size) + 1;
for (var i = 0; i < loopCount; i++) {
array.push(clob.slice(size * i, size * (i + 1)));
}
return array;
}
// converts binaryArray to base64 string
function binaryArray2base64(int8Array) {
var data = "";
var bytes = new Uint8Array(int8Array);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
data += String.fromCharCode(bytes[i]);
}
return btoa(data);
}
// a recursive function that calls itself to upload multiple files synchronously
function uploadFile(pFileIndex) {
var fileCount = 0;
var file = fileInputElem.files[pFileIndex];
var reader = new FileReader();
var uploadTarget = apex.item("P3_UPLOAD_TARGET").getValue();
reader.onload = (function(pFile) {
return function(e) {
if (pFile) {
var base64 = binaryArray2base64(e.target.result);
var f01Array = [];
f01Array = clob2Array(base64, 30000, f01Array);
apex.server.process(
'UPLOAD_FILE',
{
x01: file.name,
x02: file.type,
x03: uploadTarget,
x04: apex.item("P3_FILE_TYPE").getValue(),
x05: parent.apex.item('P2_SCREEN_TYPE').getValue(),
f01: f01Array
},
{
dataType: 'json',
success: function(data) {
if (data.j_retn_status == 'SUCCESS') {
if (fileIndex === 0) {
apex.item('P3_PRIMARY_ID').setValue(data.j_primary_id);
}
fileIndex++;
if (fileIndex < fileInputElem.files.length) {
// start uploading the next file
var d = fileIndex - 1;
uploadFile(fileIndex);
} else {
// all files have been uploaded at this point
apex.item('P3_FILES_COUNT').setValue(fileIndex);
fileInputElem.value = '';
deferredObject.resolve('done');
}
} else {
//alert('Oops! Something went terribly wrong. Please try again or contact your application administrator.' + data.j_retn_status);
$('#FILEDISP'+pFileIndex).html($('#FILEDISP'+pFileIndex).text() + '<p class="fa-window-close" aria-hidden="true"></p>' ) ;
}
}
}
);
}
}
})(file);
$('#FILEDISP'+pFileIndex).html($('#FILEDISP'+pFileIndex).text() + '<p class="fa fa-check" aria-hidden="true"></p>' ) ;
reader.readAsArrayBuffer(file);
return deferredObject.promise();
}
How can we modify it to validate image dimensions and increase image width or height before upload please?
Thank you!
You could probably do something like below, although I'd look into using a library for doing something like this in case there are gotchas for certain situations.
const MIN_WIDTH = 500;
const MIN_HEIGHT = 500;
const imageInputEl = document.getElementById('example-image');
imageInputEl.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files;
const file = fileList[0];
if ( /\.(jpe?g|png)$/i.test(file.name) ) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.src = this.result;
document.getElementById('input-image').src = this.result;
image.onload = () => {
const width = image.naturalWidth;
const height = image.naturalHeight;
let canvasWidth = MIN_WIDTH;
let canvasHeight = MIN_HEIGHT;
if (width >= MIN_WIDTH) canvasWidth = width;
if (height >= MIN_HEIGHT) canvasHeight = height;
const canvas = document.createElement("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
const ctx = canvas.getContext("2d");
ctx.drawImage(document.getElementById('input-image'), 0, 0, canvasWidth, canvasHeight);
const resizedImage = canvas.toDataURL("image/png");
document.getElementById('resized-image').src = resizedImage;
};
});
reader.readAsDataURL(file);
} else {
throw new Error('Not a valid image file.');
}
}
.container {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
<div class="container">
<input type="file"id="example-image" accept="image/png, image/jpeg">
<div>
Input Image:
</div>
<img id="input-image">
<div>
Resized Image:
</div>
<img id="resized-image">
</div>
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 am Creating QR code scanner for Browser using this plugin
https://github.com/cozmo/jsQR
and it works fine except a bug which make every thing terrible, scanning my keyboard keys or my home mat also and shows some Chinese characters, Why I chosen this plugin it works almost in every browser except IOS Chrome, Firefox
Here Is My code
var video = document.createElement("video");
var canvasElement = document.getElementById("canvas");
var canvas = canvasElement.getContext("2d");
var loadingMessage = document.getElementById("loadingMessage");
var outputContainer = document.getElementById("output");
var outputMessage = document.getElementById("outputMessage");
//var outputData = document.getElementById("outputData");
//var outputData = document.getElementById("outputData");
function drawLine(begin, end, color) {
canvas.beginPath();
canvas.moveTo(begin.x, begin.y);
canvas.lineTo(end.x, end.y);
canvas.lineWidth = 4;
canvas.strokeStyle = color;
canvas.stroke();
}
// Use facingMode: environment to attemt to get the front camera on phones
navigator.mediaDevices.getUserMedia({ video: { facingMode: { exact: "environment" } } }).then(function(stream) {
video.srcObject = stream;
video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
video.play();
requestAnimationFrame(tick);
localStream = stream;
})
.catch(function(err) {
console.log(err);
/* handle the error */
loader(false)
});
function tick() {
loadingMessage.innerText = "⌛ Loading video..."
if (video.readyState === video.HAVE_ENOUGH_DATA) {
loadingMessage.hidden = true;
canvasElement.hidden = false;
outputContainer.hidden = false;
canvasElement.height = video.videoHeight;
canvasElement.width = video.videoWidth;
canvas.drawImage(video, 0, 0, canvasElement.width, canvasElement.height);
var imageData = canvas.getImageData(0, 0, canvasElement.width, canvasElement.height);
var code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
drawLine(code.location.topLeftCorner, code.location.topRightCorner, "#FF3B58");
drawLine(code.location.topRightCorner, code.location.bottomRightCorner, "#FF3B58");
drawLine(code.location.bottomRightCorner, code.location.bottomLeftCorner, "#FF3B58");
drawLine(code.location.bottomLeftCorner, code.location.topLeftCorner, "#FF3B58");
outputMessage.hidden = true;
if(code.data != "" && code.data != undefined){
var dataQR = "qrData=" + code.data;
document.cookie = dataQR;
frmAction('serviceid',true,false);
dataQR)
alert(code.data);
vidOff();
} else {
var dataQR = "qrData=";
document.cookie = dataQR;
document.cookie = "toastMsg=Yes";
frmAction('serviceid',true,false);
vidOff();
}
} else {
outputMessage.hidden = false;
}
}
requestAnimationFrame(tick);
function vidOff() {
video.pause();
video.src = "";
video.srcObject.getVideoTracks().forEach(track => track.stop());
console.log("camera off");
}
}
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.