Register Login

Cordova Camera Plugin to Taking Pictures and Choosing Images from Media Library

Updated Jan 09, 2024

Developers often use camera plugins to access camera functionalities, images or image's local paths, or files of devices. This plugin allows users to click pictures from their devices or access any file from the gallery.

There are many standard ways to build such mobile applications, including camera plugins using HTML, CSS, and JavaScript.

Cordova is an open-source, popular framework for working with camera plugins and accessing image files. This plugin specifies a global "navigator.camera" object. It provides an API to take pictures and choose images from the device's image gallery.

This article discusses all the steps of installing the Cordova Camera Plugin to upload photos from the device camera and photo gallery.

Step 1: Install Camera Plugin

First, install the camera plugin using the given command in the command prompt:

cordova plugin add cordova-plugin-camera

Also, users can use this resource to install this plugin.

Step 2: Add buttons 

Adding buttons will allow you to click photos from the device camera or photo gallery. Use the following HTML code in your application:

Code:

<p><button id = "openDeviceCamera"> TAKE PHOTO </button> </p>
<p><button id = "openDeviceFilePicker"> SELECT PHOTO </button> </p>

Step 3: Displaying the Image 

Then, users display and add images in the hidden file for upload using the following code:

In this we will create a hidden field to store the image data in base64 format, that date we will use store the image in database,

And we will create a Paragraph <P> tag to show clicked image.

Code:

<input type = "hidden" id = "imageString" name = "imageString" value = "">
<p class = "imageBox"> <img id = "displayImage" class = "displayImage"> </img> </p>

Step 4: Add Eventlistener and Click Event

By adding the eventlistener and the Button click event, users can ensure that it loads the Cordova plugin before they start using it.

Use this JavaScript code to add the events:

document.getElementById("openDeviceCamera").addEventListener("click", openDeviceCamera);
document.getElementById("openDeviceFilePicker").addEventListener("click", openDeviceFilePicker);

Step 5: Add a function for defining camera options

Add this code in the JavaScript section to set some common settings in the application camera plugin.

For more setting

// Function to Set Camera Options
function setOptions(srcType) {
    var options = {
        // Some common settings are 20, 50, and 100
        quality: 50,
        destinationType: Camera.DestinationType.DATA_URL,
        // In this app, dynamically set the picture source, Camera or photo gallery
        sourceType: srcType,
        encodingType: Camera.EncodingType.JPEG,
        //mediaType: Camera.MediaType.PICTURE,
        //allowEdit: true,
        correctOrientation: true,
        targetHeight: 1000, 		// Scale image height to 1000 px with aspect ratio remaining constant.
        targetWidth: 1000,           // Scale image width to 1000 px with aspect ratio remaining constant.
    }
    return options;
}

Step 6: Add the main user-defined Function

Here, users will create a function named "openDeviceCamera" and pass it to the event listener as a callback. When users will press or tap the button, the <button> tag will call this function. Within this function, users will call the "navigator.camera" global object from the plugin API.

If it successfully takes the picture, the JS function will send the data to the onSuccess callback function. Otherwise, it will throw an alert with an error message. We will place this code at the bottom of index.js.

Code:

// Function to open device Camera
function openDeviceCamera() {

    var srcType = Camera.PictureSourceType.CAMERA;
    var options = setOptions(srcType);

   
navigator.camera.getPicture(function cameraSuccess(imageData) {

        displayImage(imageData);

    }, function cameraError(error) {
        console.debug("Unable to obtain picture: " + error, "app");

    }, options);
}

Step 7: Add function to add the Library

Use the given code to add a function that will open the device media library:

Code:

// Function to open device media library
function openDeviceFilePicker() {
    var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
    var options = setOptions(srcType);

   
navigator.camera.getPicture(function cameraSuccess(imageData) {

        // Display image
        // Add image data in a hidden field
        displayImage(imageData);

    }, function cameraError(error) {
        console.debug("Unable to obtain picture: " + error, "app");
		alert("Unable to obtain picture: " + error);

    }, options);
}

Step 8: Function to display the image 

Code:

// Function to display photo/image
function displayImage(imageData) {
	// Display image
    var image = document.getElementById('displayImage');
    image.src = "data:image/jpeg;base64," + imageData;
             
    // Save Image data in hidden text field
    var image = document.getElementById('imageString');
    image.value = "data:image/jpeg;base64," + imageData;
}

Step 9: Add a CSS script 

Adding the CSS code in the index.css file inside the <style> tag will create styles in the application.

Code:

.imageBox{
	width: 200px; 
	height: 200px; 
    margin-left: auto; 
    margin-right: auto;
}
.displayImage{
    max-width: 200px; 
    max-height: 200px; 
    object-fit: contain;
}

Step 10: Add Content-Security-Policy in meta tags

To Open the camera and display the image we need to update Content-Security-Policy in meta tags

data: gap: ms-appdata: https://ssl.gstatic.com 'unsafe-eval';

To run inline css and js

style-src 'self' 'unsafe-inline';

To allow device camera

media-src *
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: ms-appdata: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">

Step 11: Final Index.html file:

Code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: ms-appdata: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
		<meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
        <meta name="color-scheme" content="light dark">
        <link rel="stylesheet" href="css/index.css">		
        <title>Cordova Camera</title>
    </head>
    <body>
        <div class="app">
            <h1>Apache Cordova Camera</h1>
            <div id="deviceready" class="blink">
                <p class="event listening">Connecting to Device</p>
                <p class="event received">Device is Ready</p>
				<p><button id = "openDeviceCamera">TAKE PHOTO</button></p>
                <p><button id = "openDeviceFilePicker">SELECT PHOTO</button></p>
                <input type="hidden" id="imageString" name="imageString" value="">
                <p class="imageBox"><img id = "displayImage" class="displayImage"></img></p>
            </div>
        </div>
        <script src="cordova.js"></script>
        <script src="js/index.js"></script>
    </body>
</html>

Step 12: Final index.js file:

Code:

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    // Cordova is now initialized. Have fun!

    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    document.getElementById('deviceready').classList.add('ready');
}
// Wait for the deviceready event before using any of Cordova's device APIs.
// See https://cordova.apache.org/docs/en/latest/cordova/events/events.html#deviceready

document.getElementById("openDeviceCamera").addEventListener("click", openDeviceCamera);
document.getElementById("openDeviceFilePicker").addEventListener("click", openDeviceFilePicker);

// Function to Set Camera Options
function setOptions(srcType) {
    var options = {
        // Some common settings are 20, 50, and 100
        quality: 50,
        destinationType: Camera.DestinationType.DATA_URL,
        // In this app, dynamically set the picture source, Camera or photo gallery
        sourceType: srcType,
        encodingType: Camera.EncodingType.JPEG,
        //mediaType: Camera.MediaType.PICTURE,
        //allowEdit: true,
        correctOrientation: true,
        targetHeight: 1000, 		// Scale image height to 1000 px with aspect ratio remaining constant.
        targetWidth: 1000,           // Scale image width to 1000 px with aspect ratio remaining constant.
    }
    return options;
}

// Function to open device Camera
function openDeviceCamera() {

    var srcType = Camera.PictureSourceType.CAMERA;
    var options = setOptions(srcType);

   
navigator.camera.getPicture(function cameraSuccess(imageData) {

        displayImage(imageData);

    }, function cameraError(error) {
        console.debug("Unable to obtain picture: " + error, "app");

    }, options);
}

// Function to open device media library
function openDeviceFilePicker() {
    var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM;
    var options = setOptions(srcType);

   
navigator.camera.getPicture(function cameraSuccess(imageData) {

        // Display image
        // Add image data in a hidden field
        displayImage(imageData);

    }, function cameraError(error) {
        console.debug("Unable to obtain picture: " + error, "app");
		alert("Unable to obtain picture: " + error);

    }, options);
}

// Function to display photo/image
function displayImage(imageData) {
	// Display image
    var image = document.getElementById('displayImage');
    image.src = "data:image/jpeg;base64," + imageData;
             
    // Save Image data in hidden text field
    var image = document.getElementById('imageString');
    image.value = "data:image/jpeg;base64," + imageData;
}

function onDeviceReady() {
    // Cordova is now initialized. Have fun!

    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    document.getElementById('deviceready').classList.add('ready');
}

Now build your app using cordova build command

cordova build

Output:

Some commonly used parameters of this plugin are:

quality: This parameter specifies the image quality within the range of 0-100. By default, it is set to fifty.

destinationType

  • DATA_URL or 0: For returning base64 encoded string.
  • FILE_URI or 1: For returning image file URI.
  • NATIVE_URI or 2: For returning image native URI

sourceType

  • PHOTOLIBRARY or 0: For opening the photo library.
  • CAMERA or 1: For opening the native camera.
  • SAVEDPHOTOALBUM or 2:  For opening saved image album.

allowEdit: This parameter is for allowing image editing.

encodingType

  • JPEG or 0: For returning JPEG encoded image.
  • PNG or 1: For returning PNG encoded image.

targetWidth: It specifies the image scaling width in pixels.

targetHeight: It specifies the image scaling height in pixels.

mediaType

  • PICTURE or 0: For allowing only picture selection
  • VIDEO or 1: For allowing only video selection.
  • ALLMEDIA or 2: For allowing all media type selection.

correctOrientation: Users can use this parameter to correct the orientation of the image.

saveToPhotoAlbum: Users can use this parameter to save the image to the photo album.

popoverOptions: Users can use this parameter to set the popover location on IOS.

cameraDirection

  • FRONT or 0: Specifies the Front camera.
  • BACK or 1: Specifies the Back camera.
  • ALLMEDIA

Conclusion
This article caters to an easy and fast step-by-step installation of the Cordova camera plugin for uploading photos from a camera or media library. Also, users get different parameters of this plugin to customize the device's camera settings.


×