How To Create Customized Camera Preview In Cordova?

Cordova is a very famous and powerful platform for building hybrid mobile applications using web technology and adding a functionality of camera is quite a common requirement to incorporate in mobile apps and we might want to add our own customized UI for Camera Preview. The default Camera plugin of Cordova doesn’t provide much of a customized experience. Therefore,

In this blog, we will be exploring how to create a customized Camera preview in our Cordova app and integrate it with the user interface that meets your needs.

Steps For Creating A Customized Camera Preview

We can integrate the camera functionality in Cordova app using the Cordova-plugin camera, but this does not let us change the default UI they provide.

Prerequisites

Before we dive in, make sure you have a working node js project that’s wrapped with Cordova with Node.js, npm and Cordova CLI installed. Let’s begin now.

  • Open your node project and navigate to the Cordova directory within the project.
  • Install the camera plugin cordova-plugin-camera-preview. This plugin facilitates us and allows us to integrate HTML interactivity with the camera. 

cordova plugin add cordova-plugin-camera-preview

  • Design the user interface for your camera preview. Below is a simple react code example that shows a Flash button to toggle the flash, a Camera button to switch the camera from front to back or vica-versa, and a click button to take the picture.
<!DOCTYPE html> <html> <head>     <title>Custom Camera Preview</title> </head> <body>       <div>      <div className = "preview">       <div className="preview_header">       <button className="preview_button" onClick={() => flashOn()}>       flash            </button>       </div>       <div className="preview_footer">       <button className="preview_button" onClick={() => switchCamera()}>       Switch       </button>       <button className="preview_button" onClick={() => takePicture()}>        Click       </button>       </div>      </div>    </div> </body> </html>
Code language: HTML, XML (xml)

In the above html , we have a header that has a Flash button and a footer that has two buttons , one clicks the photo, and another switches the camera. We need to display the camera , in between these two divs.

  • Now implement the logic for the custom camera preview. The plugin provides various methods that can be used and help you enhance your user experience.
uploadCustom =  () => {    this.setState({ showPreview: true } , ()=>{    let header_height , footer_height ,preview_height ;          header_height = document.getElementsByClassName("preview_header")[0].offsetHeight;          footer_height = document.getElementsByClassName("preview_footer")[0].offsetHeight;         let body = document.body.offsetHeight          preview_height = body - (header_height + footer_height);    }    let options = {      x: 0,      y: header_height ,      width: window.screen.width ,      height: preview_height ,      camera: window.CameraPreview.CAMERA_DIRECTION.BACK,      toBack: false,      tapPhoto: false,      tapFocus: false,      previewDrag: false,      storeToFile: true,      disableExifHeaderStripping: false    };    window.CameraPreview.startCamera(options,      () => {        console.log("preview started" , options);      },      err => {        console.log("err", err);      }    );  });
Code language: JavaScript (javascript)

The above code starts the camera preview with the window.CameraPreview.startCamera() method. We’re also getting the height of the preview_header and the body, and accordingly set the x and y coordinate along with the height of the camera display.

  • We also need to toggle the flashlight.
Var flashMode = false flashOn  = () => {    // Toggle flash mode     flashMode = !flashMode;      // This callback is executed after the state is updated      let mode = flashMode        ? "on"        : "off";        window.CameraPreview.setFlashMode((mode),        () => {           console.log("Camera flash mode: " , mode);        },        (err) => { console.log("flash mode err: ", err) });    }    };
Code language: JavaScript (javascript)

In the above code, we have defined the variable flashMode, that is being toggled using a !(not) operator, and accordingly the flash mode is set.

  • Now We also want to toggle the camera from rear to front and vice versa.
switchCamera = () =>{        window.CameraPreview.switchCamera();   }
Code language: JavaScript (javascript)

  The above method will automatically switch the camera if the switch is available. 

  • Let’s Finally write the take Picture function.
takePicture = () => {    // Capture a picture    window.CameraPreview.takePicture(      { width: window.screen.width, height: 0.75 * window.screen.height,      quality: 85 },      async (fileData) => {         window.CameraPreview.stopCamera();         window.CameraPreview.hide();        let imgData = "file://" + fileData[0];        await window.resolveLocalFileSystemURL(          imgData,         async fileEntry => {          await fileEntry.file(            file => {               console.log("image file received" , file);            },          );        },          error => {            console.log("convert could not take place", error);          }        );        },        err => {          console.log("e", err);        }        );  };
Code language: JavaScript (javascript)

In the above code , we are calling the  CameraPreview.takePhoto() function which is responsible for clicking the picture. It takes 3 arguments , first being the options which include the height and width of the picture to be taken and also the quality of the picture. Next is the success callback where we are actually receiving the FilePath.

Note: Keep in mind that since we have set the storeToFile option to true , therefore , we will get an array of FilePath as a response. To get the filePath, we need to render the 0th value of the array received.

Later, we have converted the filePath into a permanent File Object using window.resolveLocalFileSystemURL, so that we can store or display the image taken. Make sure you have installed the cordova-plugin-file in order to access the resolveLocalFileSystemURL() method.

We also have called the CameraPreview.hide and CameraPreview.stop() function, so that it will stop the camera and hide the preview. You can explore other inbuilt methods included in the plugin like focusModes, zoom, color effects etc by going through the official documentation of the plugin.

  • Build and run your Cordova app.

Note: Kindly make sure that you are testing on a physical device and not on virtual devices on your laptop as it is impossible to use webcam on your VDs.

Conclusion

That was it , I hope you this blog helped you in understanding can we improve and enhance our UI by integrating customized camera Preview. In this blog, we talked about how we can create customized camera previews in our Cordova app. Combine the cordova plugin along with our custom UI components , you can match your app’s requirements. Feel free to explore and extend the given example with your own features and UI ideas.

Recent Post

Click to Copy