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

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

  • How Reinforcement Learning is Shaping the Next Generation of AI Chatbots?

    AI chatbots are no longer just about answering “What are your working hours?” or guiding users through FAQs. They’re becoming conversation partners, problem solvers and even reporting managers and sales agents. What’s driving this transformation? Enter Reinforcement Learning (RL)—a type of machine learning that’s changing the way chatbots think, learn, and respond. At Codalien Technologies, […]

  • AI Chatbots for Sales Team Automation: The Critical Role of AI Sales Assistants in Automating Your Sales Team

    Sales teams are the heart of any successful business, but managing them effectively can often feel like trying to juggle flaming swords. The constant pressure to generate leads, maintain relationships, and close deals leaves your team overwhelmed, spending more time on administrative tasks than actual selling. Here’s where AI-powered sales assistants step in to completely […]

  • Transforming HR with AI Assistants: The Comprehensive Guide

    The role of Human Resources (HR) is critical for the smooth functioning of any organization, from handling administrative tasks to shaping workplace culture and driving strategic decisions. However, traditional methods often fall short of meeting the demands of a modern, dynamic workforce. This is where our Human Resource AI assistants enter —a game-changing tool that […]

  • How Conversational AI Chatbots Improve Conversion Rates in E-Commerce?

    The digital shopping experience has evolved, with Conversational AI Chatbots revolutionizing customer interactions in e-commerce. These AI-powered systems offer personalized, real-time communication with customers, streamlining the buying process and increasing conversion rates. But how do Conversational AI Chatbots improve e-commerce conversion rates, and what are the real benefits for customers? In this blog, we’ll break […]

Click to Copy