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

  • Mastering Hyperparameter Tuning in Python: Strategies, Techniques, and Tools for Model Optimization

    Understanding various aspects of deep learning and machine learning can often feel like stepping into uncharted territory with no clue where to go. As you start exploring various algorithms and data, you realize that success is based on more than just building a raw model, it’s more about fine-tuning it to perfection. And when we […]

  • What is Transfer Learning? Exploring The Popular Deep Learning Approach

    Have you ever thought about how quickly your smartphone recognizes faces in photos or suggests text as you type? Behind these features, there’s a remarkable technique called Transfer Learning that expands the capabilities of Artificial Intelligence. Now you must be wondering- What is Transfer Learning ? Picture this: Instead of starting from the square from […]

  • LLMOps Essentials: A Practical Guide To Operationalizing Large Language Models

    When you engage with ChatGPT or any other Generative AI tool, you just type and enter your query and Tada!! You get your answer in seconds. Ever wondered how it happens and how it is so quick? Let’s peel back the curtain of the LLMs a bit. What actually happens behind the screen is a […]

  • Building Intelligent AI Models For Enterprise Success: Insider Strategies 

    Just picture a world where machines think and learn like us. It might sound like a scene straight out of a sci-fi movie, right? Well, guess what? We are already living in that world now. Today, data, clever algorithms, and AI models are changing the way businesses operate. AI models are serving as a brilliant […]

  • Introducing Google Vids in Workspace: Your Ultimate AI-Powered Video Creation Tool

    Hey there, fellow content creators and marketing gurus! Are you tired of drowning in a sea of emails, images, and marketing copy, struggling to turn them into eye-catching video presentations? Fear not, because Google has just unveiled its latest innovation at the Cloud Next conference in Las Vegas: Google Vids- Google’s AI Video Creation tool! […]

  • Achieve High ROI With Expert Enterprise Application Development

    Nowadays modern-day enterprises encounter no. of challenges such as communication breakdown, inefficient business processes, data fragmentation, data security risks, legacy system integration with modern applications, supply chain management issues, lack of data analytics and business intelligence, inefficient customer relationship management, and many more. Ignoring such problems within an organization can adversely impact various aspects of […]

Click to Copy