Accessing camera and gallery in your android application using Phonegap, HTML and JavaScript



Hello folks,

Hope you have scanned through my earlier blog which talks about building your first android application.

This blog focuses on trying to access the phone's native camera. At the end of this tutorial, you will have an android application which can capture images from your camera and gallery.

Let's get started!



I am assuming you have built your android application. If not please refer my earlier blog. I am going to continue using the application built there(MyFirstApp).

If you go to the folder in your C drive, you can see the application. The folder would contain the following files.

Step 1

config.xml

This file establishes the connection between your code and the device. It consists of the application name, application description, author details, application permissions and the connection to the different packages required for the application.

In order to build a camera application, we need to include the following package in config.xml
     <feature name="Camera">  
           <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />  
      </feature>  
Your complete config.xml will look something like this. Make you sure you replace the code in your config.xml with the code below.
 <?xml version='1.0' encoding='utf-8'?>  
 <widget id="com.example.hope" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">  
   <name>MyFirstApp</name>  
   <description>  
     My first app  
   </description>  
   <author email="me@aakshay.com" href="http://www.aakshay.com">  
     Aakshay Subramaniam  
   </author>  
   <content src="index.html" />  
   <preference name="permissions" value="none" />  
   <preference name="orientation" value="default" />  
   <preference name="target-device" value="universal" />  
   <preference name="fullscreen" value="true" />  
   <preference name="webviewbounce" value="true" />  
   <preference name="prerendered-icon" value="true" />  
   <preference name="stay-in-webview" value="false" />  
   <preference name="ios-statusbarstyle" value="black-opaque" />  
   <preference name="detect-data-types" value="true" />  
   <preference name="exit-on-suspend" value="false" />  
   <preference name="show-splash-screen-spinner" value="true" />  
   <preference name="auto-hide-splash-screen" value="true" />  
   <preference name="disable-cursor" value="false" />  
   <preference name="android-minSdkVersion" value="7" />  
   <preference name="android-installLocation" value="auto" />  
   <gap:plugin name="org.apache.cordova.battery-status" />  
      <feature name="Device">  
           <param name="android-package" value="org.apache.cordova.device" />  
      </feature>  
      <feature name="Camera">  
           <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />  
      </feature>  
   <gap:plugin name="org.apache.cordova.media-capture" />  
   <gap:plugin name="org.apache.cordova.console" />  
   <gap:plugin name="org.apache.cordova.contacts" />  
   <gap:plugin name="org.apache.cordova.device-motion" />  
   <gap:plugin name="org.apache.cordova.device-orientation" />  
   <gap:plugin name="org.apache.cordova.dialogs" />  
   <gap:plugin name="org.apache.cordova.file" />  
   <gap:plugin name="org.apache.cordova.file-transfer" />  
   <gap:plugin name="org.apache.cordova.geolocation" />  
   <gap:plugin name="org.apache.cordova.globalization" />  
   <gap:plugin name="org.apache.cordova.inappbrowser" />  
   <gap:plugin name="org.apache.cordova.media" />  
   <gap:plugin name="org.apache.cordova.network-information" />  
   <gap:plugin name="org.apache.cordova.splashscreen" />  
   <gap:plugin name="org.apache.cordova.vibration" />  
   <icon src="icon.png" />  
   <icon gap:platform="android" gap:qualifier="ldpi" src="www/res/icon/android/icon-36-ldpi.png" />  
   <icon gap:platform="android" gap:qualifier="mdpi" src="www/res/icon/android/icon-48-mdpi.png" />  
   <icon gap:platform="android" gap:qualifier="hdpi" src="www/res/icon/android/icon-72-hdpi.png" />  
   <icon gap:platform="android" gap:qualifier="xhdpi" src="www/res/icon/android/icon-96-xhdpi.png" />  
   <gap:splash gap:platform="android" gap:qualifier="port-ldpi" src="www/res/screen/android/screen-ldpi-portrait.png" />  
   <gap:splash gap:platform="android" gap:qualifier="port-mdpi" src="www/res/screen/android/screen-mdpi-portrait.png" />  
   <gap:splash gap:platform="android" gap:qualifier="port-hdpi" src="www/res/screen/android/screen-hdpi-portrait.png" />  
   <gap:splash gap:platform="android" gap:qualifier="port-xhdpi" src="www/res/screen/android/screen-xhdpi-portrait.png" />  
   <access origin="*" />  
 </widget>  

Step 2

index.html

You would find the legendary index.html in the www folder. This file is the page that you will see when you run your mobile application.
In order to access the device camera, we need to add the following code in javascipt. This uses the cordova.js file.
 navigator.camera.getPicture(onPhotoDataSuccess, onFail, {   
      quality: 50,   
      destinationType: destinationType.DATA_URL   
     });  
Your final index.html would look something like this. Make you sure you replace the code in your index.html with the code below.
 <!DOCTYPE html>  
 <html>  
 <head>  
   <title>Capture Photo</title>  
   <script type="text/javascript" charset="utf-8" src="cordova.js"></script>  
   <script type="text/javascript" charset="utf-8">  
     var pictureSource; // picture source  
     var destinationType; // sets the format of returned value  
     // Wait for device API libraries to load  
     //  
     document.addEventListener("deviceready", onDeviceReady, false);  
     // device APIs are available  
     //  
     function onDeviceReady() {  
       pictureSource = navigator.camera.PictureSourceType;  
       destinationType = navigator.camera.DestinationType;  
     }  
     // Called when a photo is successfully retrieved  
     //  
     function onPhotoDataSuccess(imageData) {  
       // Uncomment to view the base64-encoded image data  
       // console.log(imageData);  
       // Get image handle  
       //  
       var smallImage = document.getElementById('smallImage');  
       // Unhide image elements  
       //  
       smallImage.style.display = 'block';  
       // Show the captured photo  
       // The in-line CSS rules are used to resize the image  
       //  
       smallImage.src = "data:image/jpeg;base64," + imageData;  
     }  
     // Called when a photo is successfully retrieved  
     //  
     function onPhotoURISuccess(imageURI) {  
       // Uncomment to view the image file URI  
       // console.log(imageURI);  
       // Get image handle  
       //  
       var largeImage = document.getElementById('largeImage');  
       // Unhide image elements  
       //  
       largeImage.style.display = 'block';  
       // Show the captured photo  
       // The in-line CSS rules are used to resize the image  
       //  
       largeImage.src = imageURI;  
     }  
     // A button will call this function  
     //  
     function capturePhoto() {  
       // Take picture using device camera and retrieve image as base64-encoded string  
       navigator.camera.getPicture(onPhotoDataSuccess, onFail, {  
         quality: 50,  
         destinationType: destinationType.DATA_URL  
       });  
     }  
     // A button will call this function  
     //  
     function capturePhotoEdit() {  
       // Take picture using device camera, allow edit, and retrieve image as base64-encoded string  
       navigator.camera.getPicture(onPhotoDataSuccess, onFail, {  
         quality: 20,  
         allowEdit: true,  
         destinationType: destinationType.DATA_URL  
       });  
     }  
     // A button will call this function  
     //  
     function getPhoto(source) {  
       // Retrieve image file location from specified source  
       navigator.camera.getPicture(onPhotoURISuccess, onFail, {  
         quality: 50,  
         destinationType: destinationType.FILE_URI,  
         sourceType: source  
       });  
     }  
     // Called if something bad happens.  
     //  
     function onFail(message) {  
       alert('Failed because: ' + message);  
     }  
   </script>  
 </head>  
 <body>  
   <button onclick="capturePhoto();">Capture Photo</button>  
   <br>  
   <button onclick="capturePhotoEdit();">Capture Editable Photo</button>  
   <br>  
   <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button>  
   <br>  
   <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button>  
   <br>  
   <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />  
   <img style="display:none;" id="largeImage" src="" />  
 </body>  
 </html>  

Step 3

Now build you application. Type the following in command prompt.
 C:\CameraApp>cordova build android  
Now navigate to the path specified in the command prompt to find your APK.

Step 4

Install this APK in your device or an emulator. When you run the app, you will see an interface like this.












That's it! Now your application can access the camera and the gallery. Have fun.

Do check my next blog where I explain Push Notifications for android using Phonegap and Google Cloud Messaging.

Peace and cheers!

Popular posts from this blog

Building your first Phonegap android application with HTML and JavaScript