Welcome folks today in this blog post we will be capturing image from webcam and encode it to base64 dataurl in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="container"> <video width="200" height="200" autoplay="true" id="video"> </video> </div> <button onclick="capture()">Capture</button> <br> <br/> <canvas id="canvas" style="overflow:auto"></canvas> <br><br/> <p> Image Converted to String: </p> <p id="printresult"></p> </body> </html> |
As you can see in the above html code we have the video element inside it we are displaying the live webcam video feed of the user. And after that we have the simple button to capture the image from the webcam and also we are attaching the onclick event listener. And we are calling the capture() method and after that we have the canvas tag inside it we are displaying the captured image and also inside the paragraph we are displaying the base64 dataurl of the captured image
And now we need to define the javascript
code which will actually render the webcam live
feed of the user as shown below
1 2 3 4 5 6 7 8 9 10 11 |
var video = document.querySelector("#video"); if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { video.srcObject = stream; }) .catch(function (err0r) { console.log("Something went wrong!"); }); } |
As you can see in the above javascript code we are getting the reference of the video
element and after that we are using the navigator api inside it we are using the getUserMedia()
method and after that we are attaching the webcam live feed
to the srcobject of the video.
And now we will be defining the capture()
method to capture the image from the webcam as shown below.
1 2 3 4 5 6 7 8 9 10 |
function capture() { var canvas = document.getElementById('canvas'); var video = document.getElementById('video'); canvas.width = 200; canvas.height = 200; canvas.getContext('2d').drawImage(video, 0, 0, 200,200); document.getElementById("printresult").innerHTML = canvas.toDataURL(); } |
As you can see in the above code we are getting the references of the canvas and the video element. And after that we are using the drawImage()
method to draw the image on the canvas and then we are using the getDataURL()
method to convert the canvas to the base63 data url. And after that we are showing the base64 code of the image inside the browser