Taking Photos Using PhoneGap Camera API

While working on a PhoneGap application , there was an requirement to take photo using device camera and upload in the sever. And PhoneGap provides an easy way to interact with the device camera and take photo using Camera API.

Description: Basically there are two ways to take photo from mobile device.

1. Taking photos using Camera
2. Taking photos from Library/Gallery

So here we will  focus on displaying the image in our application using both ways. PhoneGap provides the camera.getPicture method which can help us to invoke camera and take images from mobile devices.

Here are the steps below that we need to follow to invoke Camera API.

1. Include the Phonegap/Cordova javascript file inside your HTML page.
2. Create a function to get the images from specified source like from library and taking photo instantly.

// It will take photo by capturing image using device camera.
function TakePhotoUsingCamera() {
TakePhoto(Camera.PictureSourceType.CAMERA);      };

// It will take photo from existing library/gallery.
function TakePhotoFromLibrary() {

3. Create a function to take photo according to user choice.

function TakePhoto(sourceType) {
var camOptions = {
destinationType: Camera.DestinationType.DATA_URL,
sourceType: sourceType,
correctOrientation: true
navigator.camera.getPicture(OnSuccess, OnFailure, camOptions);

4. Create a function to display the success message and to get the image in base64 format.

function OnSuccess(imageData) {
navigator.notification.alert("Image taken successfully.");
var imageSource = "data:image/jpeg;base64," + imageData;
$('.previewImage ').attr('src', imageSource);

5. Create a function to display the error message.

function OnFailure(message) {
navigator.notification.alert("Failed because: " + message);

6. Create two button to call the function to get the image.

<button onclick="TakePhotoUsingCamera();">Take Photo Using Camera</button>

<button onclick="TakePhotoFromLibrary();">Take Photo From Library</button>

7. Create an image tag to preview the image to user.

<img style=”width:100px; height:100px;” />

From the above example we learn how to take images and preview the same in mobile devices using PhoneGap Camera API.


Written By: Sourabha Kumar Sahoo, Software Developer, Mindfire Solutions


2 thoughts on “Taking Photos Using PhoneGap Camera API

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s