cordova-camera-plugin-tutorial
cordova-camera-plugin-tutorial
cordova-camera-plugin-tutorial

Hey friend,

Thinking about accessing 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 camera plugin

  • Used for accessing device camera
  • You can access 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 camera or existing gallery in cordova applications. After taking a picture we can use FILE_URI or DATA_URI for displaying picture to user.

Create new project & add 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);

Accessing device gallery

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

Why base64 string?

Incase, If you need to store images on database instead of 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!

Hope this cordova plugin camera tutorial helps you lot. If you faced any issue, feel free to comment below