Learn how to implement the webcam feature to take snapshots on your hybrid application with webcamjs and Electron framework.
Preparing the camera
To handle the camera task, we are going to use webcamjs. WebcamJS is a small (~3K minified and gzipped) standalone JavaScript library for capturing still images from your computer's camera, and delivering them to you as JPEG or PNG Data URIs. WebcamJS uses HTML5 getUserMedia.
To get started with this plugin, add it to our electron project using :
npm install webcamjs --save
Then we'll be able to require it with javascript, but before, create the basic html structure in your main html file (a div for the camera and a button to start or stop it):
<!--You can change the dimensions of the camera with height and weight, (text align and margin is just for center the image)-->
<div id="camdemo" style="width: 320px; height: 240px; text-align: center; margin: 0 auto;"></div>
<br>
<div style="text-align:center;">
<input type="button" id="start" value="Start / Shut down camera"/>
</div>
Then make it work with javascript, create a event listener for the button and use the plugin to start or enable the camera :
// A flag to know when start or stop the camera
var enabled = false;
// Use require to add webcamjs
var WebCamera = require("webcamjs");
document.getElementById("start").addEventListener('click',function(){
if(!enabled){ // Start the camera !
enabled = true;
WebCamera.attach('#camdemo');
console.log("The camera has been started");
}else{ // Disable the camera !
enabled = false;
WebCamera.reset();
console.log("The camera has been disabled");
}
},false);
Finally use npm start
in the command prompt to start the project and test the camera !
If you need to, you can see more demos of webcamjs here.
Saving the image to the desktop
Thanks to the plugin, the snapshot will be easy to handle, but the plugin will return only a base64 string of the image. To generate the base64 string use the snap
function of WebCamera (read how to use it here).
Now to save the image we need to process the base64 string and save it in a file. Add a button to save it.
<input type="button" id="savefile" value="Save photo in Desktop"/>
Add the dialog dependency to create a dialog to save the file easily, take the snapshot of the camera and write it to the file :
var remote = require('remote'); // Load remote component that contains the dialog dependency
var dialog = remote.require('dialog'); // Load the dialogs component of the OS
var fs = require('fs'); // Load the File System to execute our common tasks (CRUD)
// return an object with the processed base64image
function processBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),response = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
}
document.getElementById("savefile").addEventListener('click',function(){
if(enabled){
WebCamera.snap(function(data_uri) {
// Save the image in a variable
var imageBuffer = processBase64Image(data_uri);
// Start the save dialog to give a name to the file
dialog.showSaveDialog({
filters: [
{ name: 'Images', extensions: ['png'] },
]
},function (fileName) {
if (fileName === undefined){
console.log("You didn't save the file because you exit or didn't give a name");
return;
}
// If the user gave a name to the file, then save it
// using filesystem writeFile function
fs.writeFile(fileName, imageBuffer.data, function(err) {
if(err){
console.log("Cannot save the file :'( time to cry !");
}else{
alert("Image saved succesfully");
}
});
});
});
}else{
console.log("Please enable the camera first to take the snapshot !");
}
},false);
The dialog should work like a charm and you'll be able to save the image with the system save dialog (read more about the lifecycle of a file, how to save it with dialogs etc here):
And the image saved on the desktop :
Notes
- You can change the format of the image changing the image_format property in the initialization of webcamjs
- If the camera is being used by another program you'll see a black screen. Till the date there's no way of detect if the camera is being used by another program.
- Visit the examples repository of electron by Our Code World to see this example
Have fun