Learn App Making
with Ionic, Cordova & Flutter.

Start Here Buy Themes

Take Picture using Cordova

Hey Everyone,

Thinking about accessing the device camera or gallery using PhoneGap or Cordova?. I have written a simplified step by step tutorial for you.

Before starting, we’ll understand the usage of the camera plugin

  • Used for accessing device camera
  • You can access the existing image gallery
  • Access image local path
  • Access base-64 string of that image
  • crop images & more

cordova plugin camera is used for getting the picture from the camera or existing gallery in Cordova applications. After taking a picture we can use FILE_URI or DATA_URI for displaying pictures to the user.

Create a new project & add a plugin

cordova create camera
cd camera
cordova platform add android
cordova plugin add cordova-plugin-camera

Syntax

navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);

cameraOptions

by modifying cameraOptions, you can do many thing with camera plugin such as

Accessing device Camera

This example, we’re accessing device camera then editing that image & save that image to gallery

    var cameraOptions = {
        sourceType: Camera.PictureSourceType.CAMERA,
        saveToPhotoAlbum: true,
        allowEdit: true
    };

    navigator.camera.getPicture(function(result) {
        console.log(result);
        document.getElementById('image').src = result;
    }, function(error) {
        console.log(error);
    }, cameraOptions);

This code allows you to access the image from existing device gallery and return as base64 string, we’re displaying that string into images

Why the base64 string?

In case, If you need to store images on the database instead of the file system, you can use this (but not recommended for high-quality pictures)

    var galleryOptions = {
        sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
        destinationType: Camera.DestinationType.DATA_URL
    };

    navigator.camera.getPicture(function(result) {
        console.log(result);

        //displaying base64 string as image
        document.getElementById('image').src = "data:image/jpeg;base64," + result;

    }, function(error) {
        console.log(error);
    }, galleryOptions);

Cheers!