Your Customers are Mobile, you will be too …

jQuery Mobile: Accessing the Photo Album with Cordova 2.0

In this tutorial we will show you how to access the phones internal photo album within your jQuery Mobile app. By the end of this article you will be able to go  to the photo album, select and image and return to the same page and display the image selected inside your jQuery Mobile app. We will be adding to the code from the previous tutorial so check it out.

For this like our last tutorial we will be using Cordova 2.0 to acheive this. If you have not done this tutorial it is advised you go take a quick look at it now before proceeding. jQuery Mobile: use Phone Camera using Cordova 2.0

jQuery Mobile Accessing the Photo Album: The Files we need

If you have already done the previous tutorial on using the camera you can skip this section and go straight to the JavaScript.

Before we begin anything we need to make sure we have all the files in place we need to make the camera work. As we are using Cordova 2.0 to do this lets start with that.

The latest version of Cordova is available here free to download. http://phonegap.com/download

Download the latest version of phonegap. The only file are interested in is the latest Cordova.js file which is cordova-2.0.0.js at present. Copy this file to the folder of your in which store all your jQuery Mobile javascripts.

Now in the head of your HTML file you need to call the file just like you have the rest of your .js files.

Place the following line in your head of your HTML file.

<script src="path_to_file/cordova-2.0.0.js" type="text/javascript"></script>

Replace path to file with the folder your Cordova file is in.

Now we are ready to proceed.

jQuery Mobile Accessing the Photo Album: The JavaScript

Our JavaScript code in the head of our HTML document from last lesson should have looked like this when we were finished.

<script type="text/javascript" charset="utf-8">
 var pictureSource; // picture source
 var destinationType; // sets the format of returned value 

 // Wait for Cordova to connect with the device
 document.addEventListener("deviceready",onDeviceReady,false);

 // Cordova is ready to be used!
 function onDeviceReady() {
 pictureSource=navigator.camera.PictureSourceType;
 destinationType=navigator.camera.DestinationType;
 }

 // Take picture using device camera and retrieve image as base64-encoded string
 function capturePhoto() {
 navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, allowEdit : true,
 destinationType: destinationType.DATA_URL });
 }

 // Called if something bad happens. 
 function onFail(message) {
 alert('Failed because: ' + message);
 }

 function onPhotoDataSuccess(imageData) {
 // Uncomment to view the base64 encoded image data
 // console.log(imageData);

 // Unhide image elements
 largeImage.style.display = 'block';

 // Show the captured photo
 // The inline CSS rules are used to resize the image
 largeImage.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 inline CSS rules are used to resize the image
 largeImage.src = imageURI;
 }
 </script>

This code remains untouched if you are going to be using the camera as well as the photo album. If you are only accessing the photo album and are not taking any photos the only functions that need to be removed are the capturePhoto and onPhotoDataSuccess functions. The rest of the functions are very much needed to access and display our images from the photo gallery.

To access the photo gallery we need to add the following function to our previous JavaScript Code.

// A button will call this function to retrieve photos from the album
 function getPhoto(source) {

   // Retrieve image file location from specified source
   navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, 
     destinationType: destinationType.FILE_URI,
     sourceType: source });
 }

Add this snippet of code inside your Script tags in the head of your document. As you can see looking at our previous code the onPhotoURISuccess and onFail functions that we need to make the photo album retrieve and image are already in place from when we used the camera earlier. As are the other functions we used previously to display the image we took.

Our finished code should now look like this:

<script type="text/javascript" charset="utf-8">
 var pictureSource; // picture source
 var destinationType; // sets the format of returned value 

 // Wait for Cordova to connect with the device
 document.addEventListener("deviceready",onDeviceReady,false);

 // Cordova is ready to be used!
 function onDeviceReady() {
   pictureSource=navigator.camera.PictureSourceType;
   destinationType=navigator.camera.DestinationType;
 }

 // Take picture using device camera and retrieve image as base64-encoded string
 function capturePhoto() {
   navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, allowEdit : true,
   destinationType: destinationType.DATA_URL });
 }

 // Called if something bad happens. 
 function onFail(message) {
   alert('Failed because: ' + message);
 }

 function onPhotoDataSuccess(imageData) {
   // Uncomment to view the base64 encoded image data
   // console.log(imageData);

   // Get image handle
   var largeImage = document.getElementById('largeImage');

   // Unhide image elements
   largeImage.style.display = 'block';

   // Show the captured photo
   // The inline CSS rules are used to resize the image
   largeImage.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 inline CSS rules are used to resize the image
   largeImage.src = imageURI;
 }
 // A button will call this function to retrieve photos from the album
 function getPhoto(source) {

   // Retrieve image file location from specified source
   navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, 
     destinationType: destinationType.FILE_URI,
     sourceType: source });
 }
</script>

How that our JavaScript is in place in the head of our HTML doc is time to add the button to our page that enables our user to access the photo gallery.

jQuery Mobile Accessing the Photo Album: The HTML

After our last tutorial our content div on our jQuery Mobile page should have looked like this:

<div data-role="content"> 
  <button data-theme="d" onclick="capturePhoto();">Capture Photo</button>  
  <img style="display:none;width:100%;" id="largeImage" src="" /> <br>
</div>

Just like our last tutorial all we need need to do is add another button with an onclick call attached to it to access the photo album.

 <button data-theme="d" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Browse Photos</button>

This time the onclick call activates the getPhoto function and tells it the picture source is the Photo library.

So now our HTML code should look like this:

<div data-role="content"> 
  <button data-theme="d" onclick="capturePhoto();">Capture Photo</button> 
  <button data-theme="d" onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Browse Photos</button> 
  <img style="display:none;width:100%;" id="largeImage" src="" /> <br>
</div>

The getPhoto function once it has completed will then use the same JavaScript we used with the camera to display in the same place as before.

Hope you found this helpful and see you again soon. Our next tutorial in this series will be about uploading these images to a server.

11 Responses to jQuery Mobile: Accessing the Photo Album with Cordova 2.0

  • Great post. I was checking continuously this blog and I am impressed! Extremely helpful information specifically the last part :) I care for such information a lot. I was seeking this certain information for a long time. Thank you and best of luck.

  • No joy. No errors, just nothing happening at all. Are there permissions I need to set in xcode to enable camera/album access?

    • no there is no other code. Check your code matches what is in the tutorial and that the external files you are using match those used in the tutorial

  • Great tutorial! I was trying for six hours to get this to work and couldn’t find success with any other tutoria on the internet! I had this working within 30 minutes of finding your post

    great! thanks so much!!!

  • Thanks for the great tutorial Stephen!
    When are you planning to do the next one? I can’t wait to learn how to upload those images to the server…….

  • Do you mind if I quote a couple of your articles as long as I
    provide credit and sources back to your site? My blog is in
    the exact same area of interest as yours and my users would certainly benefit from
    a lot of the information you present here. Please let me
    know if this ok with you. Thanks!

  • thx, couldn’t believe it just worked after copy & paste and deploying the code with phonegap

  • Will this work on iphone?

Leave a Reply

Please buy me a Coffee

Help a starving student to drink more coffee

Follow us on: