Camera Plugin Example – Phonegap / Apache Cordova

camera-plugin-example-phonegap-apache-cordova
camera-plugin-example-phonegap-apache-cordova

 

This Tutorial will explain how to take picture / photo using apache cordova / phonegap. Here we’re going to use Camera Plugin https://github.com/apache/cordova-plugin-camera. Camera Plugin is useful for taking a photo from camera or saved photo Gallery.

How to Capture photo using phonegap / Apache Cordova ?

Step 1: Create a PhoneGap project

cordova create CameraApp com.phonegappro.cameraApp CameraApp

Step 2: Change your directory

cd CameraApp

Step 3: Add Camera Plugin

cordova plugin add cordova-plugin-camera

 

navigator.camera.getPicture method is used for taking a picture from camera / photo gallery. we can pass the option for navigator.camera.getPicture method such as image quality for crop photo, default height and width and more.
The Option are,

navigator.camera.getPicture(SuccessFunction, FailedFunction ,{
quality : 75,
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
saveToPhotoAlbum: false });

Here quality for image quality, destinationType for destination type. It can be URL format or Base-64 Format, sourceType defines image source that can be a CAMERA or SAVEDPHOTOALBUM and saveToPhotoAlbum saves your output in your SD Card and using encodingType you can save your images using PNG or JPEG format

Camera plugin example code for taking photo from camera

<input type="button" onclick="takephoto()" value="Take Photo Image Base64"/>
<img src="" id="myImage" height="200px" width="200px"/>
function takephoto()
{
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
}
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
document.getElementById("text1").innerHTML = imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}

Camera plugin example code for taking photo from gallery

<input type="button" onclick="takephoto()" value="Take Photo Image Base64"/>
<img src="" id="myImage" height="200px" width="200px"/>
function takephoto()
{
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.SAVEDPHOTOALBUM
});
}
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
document.getElementById("text1").innerHTML = imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
  • Was this Helpful ?
  • Yes   No
  • Frank Zhang

    how to select multiple images from gallery?

  • tekticks support

    how to use crop plugin in the above code.