Take Photo From Webcam Using Javascript (Example Code)

webcam example

If you want to take a picture from your computer or laptop webcam, you can easily do that using Javascript, there's a library called webcamjs, it's really simple and easy to use. 

Here's an example code of how you can take a picture from a webcam and then upload it to the server.

1. First grab the Webcamjs CDN and paste it before body tag of your HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.26/webcam.js" integrity="sha256-JTH6WxFs/GvXkgGMSYlAXBawtdhTdyYA3+7hhkBG6/o=" crossorigin="anonymous"></script>

2. Now create the HTML for camera preview and camera result

<div id="my_camera"></div>
<input type=button value="Configure" onClick="configure()">
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<div id="results" ></div>
<input type=button value="Save Snapshot" onClick="saveSnap()">

3. Then the full Javascript code for taking picture and upload to server

<!-- CSS -->
<style>
#my_camera{
 width: 320px;
 height: 240px;
 border: 1px solid black;
}
</style>
<!-- -->
 <div id="my_camera"></div>
 <input type=button value="Configure" onClick="configure()">
 <input type=button value="Take Snapshot" onClick="take_snapshot()">
 <input type=button value="Save Snapshot" onClick="saveSnap()">
 
 <div id="results" ></div>
 
 <!-- Script -->
 <script type="text/javascript" src="webcamjs/webcam.min.js"></script>
 <!-- Code to handle taking the snapshot and displaying it locally -->
 <script language="JavaScript">
 
 // Configure a few settings and attach camera
 function configure(){
  Webcam.set({
   width: 320,
   height: 240,
   image_format: 'jpeg',
   jpeg_quality: 90
  });
  Webcam.attach( '#my_camera' );
 }
 // A button for taking snaps
 // preload shutter audio clip
 var shutter = new Audio();
 shutter.autoplay = false;
 shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';
 function take_snapshot() {
  // play sound effect
  shutter.play();
  // take snapshot and get image data
  Webcam.snap( function(data_uri) {
  // display results in page
  document.getElementById('results').innerHTML = 
   '<img id="imageprev" src="'+data_uri+'"/>';
  } );
  Webcam.reset();
 }
function saveSnap(){
 // Get base64 value from <img id='imageprev'> source
 var base64image = document.getElementById("imageprev").src;
 Webcam.upload( base64image, 'upload.php', function(code, text) {
  console.log('Save successfully');
  //console.log(text);
 });
}
</script>

4. I am using the PHP for its server upload proccess, it's the easiest

<?php
// new filename
$filename = 'pic_'.date('YmdHis') . '.jpeg';
$url = '';
if( move_uploaded_file($_FILES['webcam']['tmp_name'],'upload/'.$filename) ){
 $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/upload/' . $filename;
}
// Return image url
echo $url;

If the code doesn't work, always consult the Browser console by pressing F12, then select tab Console, if there's an error you should fix it first.

For full documentation of using WebcamJS, you can go to their official github repository for documentation on how to use and customize it here jhuckaby/webcamjs.

Browser based application is the easiest way to build a user interface, with the help of Javascript, you can develop front end applications, faster, with sophisticated look. 

The benefit of building UI on the also the fact that the availability of libraries you can use to ease your UI development, you can just grab so many already exists libraries, read the API and then you can start customising and make your application useful and user  friendly. 


Popular posts from this blog

ERROR 1348 Column Password Is Not Updatable When Updating MySQL Root Password

How To Create Spring Boot Project Using Netbeans

Spring Kafka - How to use ReplyingKafkaTemplate send and reply synchronously