Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active July 26, 2023 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/a6ba798b76f9eeb446bccbf2f393695f to your computer and use it in GitHub Desktop.
Save code-boxx/a6ba798b76f9eeb446bccbf2f393695f to your computer and use it in GitHub Desktop.
Javascript Take Photo With Webcam

JAVASCRIPT TAKE PHOTO WITH WEBCAM

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
// https://netcell.netlify.com/blog/2016/04/image-base64.html
// (A) BASE64 DECODE UPLOADED IMAGE
$data = explode(",", $_POST["snap"]);
$data = base64_decode($data[1]);
// (B) SAVE IMAGE
$file = fopen("snap.jpg", "w");
fwrite($file, $data);
fclose($file);
echo "OK";
/* (A) ENTIRE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body, html {
padding: 0; margin: 0;
color: #fff;
background: #101010;
}
body {
max-width: 1000px;
margin: 0 auto;
}
#cam-live, #cam-snaps, #cam-controls { width: 100%; }
/* (B) LIVE FEED VIDEO */
#cam-live {
height: 500px;
object-fit: cover;
}
/* (C) CONTROL BUTTONS */
#cam-controls { display: flex; }
#cam-controls input {
flex-grow: 1;
border: 0;
color: #fff;
background: #333;
font-size: 32px;
padding: 20px 0;
cursor: pointer;
}
/* (D) SNAPSHOTS */
#cam-snaps {
display: grid;
grid-template-columns: repeat(4, 25%);
min-height: 150px;
background: #000;
}
#cam-snaps canvas {
max-height: 150px;
width: auto;
}
<!DOCTYPE html>
<html>
<head>
<title>Webcam Capture Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- https://fonts.google.com/icons -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="webcam.css">
<script defer src="webcam.js"></script>
</head>
<body>
<!-- (A) VIDEO LIVE FEED -->
<video id="cam-live" autoplay></video>
<!-- (B) CONTROLS -->
<div id="cam-controls">
<input type="button" id="cam-take" class="material-icons"
value="photo_camera" onclick="webcam.take()" disabled>
<input type="button" id="cam-save" class="material-icons"
value="download" onclick="webcam.save()" disabled>
<input type="button" id="cam-upload" class="material-icons"
value="upload" onclick="webcam.upload()" disabled>
</div>
<!-- (C) SNAPSHOTS -->
<div id="cam-snaps"></div>
</body>
</html>
var webcam = {
// (A) INITIALIZE - GET USER PERMISSION TO ACCESS CAMERA
hVid : null, hSnaps :null,
init : () => {
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
// (A1) GET HTML ELEMENTS
webcam.hVid = document.getElementById("cam-live"),
webcam.hSnaps = document.getElementById("cam-snaps");
// (A2) "LIVE FEED" WEB CAM TO <VIDEO>
webcam.hVid.srcObject = stream;
// (A3) ENABLE BUTTONS
document.getElementById("cam-take").disabled = false;
document.getElementById("cam-save").disabled = false;
document.getElementById("cam-upload").disabled = false;
})
.catch(err => console.error(err));
},
// (B) SNAP VIDEO FRAME TO CANVAS
snap : () => {
// (B1) CREATE NEW CANVAS
let cv = document.createElement("canvas"),
cx = cv.getContext("2d");
// (B2) CAPTURE VIDEO FRAME TO CANVAS
cv.width = webcam.hVid.videoWidth;
cv.height = webcam.hVid.videoHeight;
cx.drawImage(webcam.hVid, 0, 0, webcam.hVid.videoWidth, webcam.hVid.videoHeight);
// (B3) DONE
return cv;
},
// (C) PUT SNAPSHOT INTO <DIV> WRAPPER
take : () => webcam.hSnaps.appendChild(webcam.snap()),
// (D) FORCE DOWNLOAD SNAPSHOT
save : () => {
// (D1) TAKE A SNAPSHOT, CREATE DOWNLOAD LINK
let cv = webcam.snap(),
a = document.createElement("a");
a.href = cv.toDataURL("image/png");
a.download = "snap.png";
// (D2) "FORCE DOWNLOAD" - MAY NOT ALWAYS WORK!
a.click(); a.remove(); cv.remove();
// (D3) SAFER - LET USERS MANUAL CLICK
// webcam.hSnaps.appendChild(a);
},
// (E) UPLOAD SNAPSHOT TO SERVER
upload : () => {
// (E1) APPEND SCREENSHOT TO DATA OBJECT
var data = new FormData();
data.append("snap", webcam.snap().toDataURL("image/jpeg", 0.6));
// (E2) UPLOAD SCREENSHOT TO SERVER
fetch("save.php", { method:"post", body:data })
.then(res => res.text())
.then(txt => alert(txt));
}
};
window.addEventListener("load", webcam.init);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment