I wrote this article to show you how to access your smartphone image gallery. Attached to this article will be a working example you can reuse for your needs.
 
 

Note: If this tutorial was helpful, need further clarification, something is not working or do you have a request for another Ionic post? Furthermore, if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here, again leave me a comment below. I'm here to help you, I expect the same from you. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com, or follow and mention me on twitter (@gajotres). Thanks and have a nice day!

PS. If you want my help, if possible (even if it takes you some time to do that), create a working example I can play with. Use Plunker for AngularJS based questions or jsFiddle for jQuery/jQuery Mobile based questions.


 

Table of Contents

 
Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)
 

Preparation

 
If you don’t have a preset development environment then make sure you have these:
 
  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova
No previous Ionic Framework experience, find more information here: Ionic Framework | Installation Guide.
 

1. Update Ionic & Cordova

 
This tutorial requires the latest possible nodeJs version you can use. You will not be able to download/update latest Ionic Framework or Cordova without it.
 
Now we can update Ionic, and Cordova. Just be warned, older versions may not work with this tutorial:
 
npm update -g cordova ionic
 

2. Create a New Project

 
ionic start IonicImagePickerDemo blank
cd IonicImagePickerDemo
 
Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.
 
This example requires Android platform:
 
ionic platform add android
 
For MacOS users, do it like this:
 
ionic platform add ios
 

3. Download ngCordova archive

 
ngCordova is a collection of 63+ AngularJS extensions on top of the Cordova API that make it easy to build, test, and deploy Cordova mobile apps with AngularJS. While we can make this work without ngCordova, it’s much more practical this way. This collection also holds many Ionic Framework compatible plugins.
 
Download ngCordova zip file, here’s site link:
 
Official Site Docs Download Link
 
 
Unzip this archive, find a file name called: ng-cordova.min.js, it should be available at this location: ng-cordova-master\dist\.
 
Open your newly created project directory and copy ng-cordova.min.js to this location: IonicImagePickerDemo\www\js.
 
Now include this location to index.html located at IonicImagePickerDemo\www; add it above cordova.js file, like this:
 
<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
 

4. Install Cordova Image Picker Plugin

 
Add required plugins:
 
cordova plugin add https://github.com/wymsee/cordova-imagePicker.git
cordova plugin add cordova-plugin-whitelist
cordova plugin add org.apache.cordova.contacts
cordova plugin add https://github.com/hazemhagrass/phonegap-base64 
 
Install Whitelist plugin only if you’re using Cordova 4.0 +. Without it you’ll receive “Application Error: There was a network error.” error. On the other hand, add last two plugins only if you’re intending to reuse my example. They’re not required for Image Picker.
 
GitHub - Image Picker
 
 
 

Development

 
At this point, you should have everything set up and ready, we can start working on our example.
 
Go to IonicImagePickerDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:
 
var app = angular.module('starter', ['ionic', 'ngCordova'])
 
Open index.html file, add a controller to ion-pane directive:
 
  <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">Image Picker Example</h1>
      </ion-header-bar>
      <ion-content ng-controller="ImagePickerController">
      </ion-content>
   </ion-pane>
 
Initialize this controller in app.js file; don’t forget to inject $cordovaImagePicker service. We will also need $ionicPlatform, like this:
 
app.controller('ImagePickerController', function($scope, $cordovaImagePicker, $ionicPlatform) {

});
 
If you’re using Cordova 4+ you will need to check if there’s a Whitelist plugin installed with your project. If you have it, add this security meta tag to your index.html HEAD content:
 
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
 
Without it your application will throw an error during the app initialization, after that it will constantly throwing no security meta-tag found. While not a blocking point, constant console log warnings will make it hard to do any debugging.
 
We will use next function to trigger a notification, don’t forget to wrap it into Cordova deviceready event (or Ionic ready event depending on your project):
 
$scope.getImageSaveContact = function() {		
        // Image picker will load images according to these settings
	var options = {
		maximumImagesCount: 1, // Max number of selected images, I'm using only one for this example
		width: 800,
		height: 800,
		quality: 80            // Higher is better
	};

	$cordovaImagePicker.getPictures(options).then(function (results) {
                // Loop through acquired images
		for (var i = 0; i < results.length; i++) {
			console.log('Image URI: ' + results[i]);   // Print image URI
		}
	}, function(error) {
		console.log('Error: ' + JSON.stringify(error));    // In case of error
	});
};	
 
id is the most important part of this function. It’s a number that represents your local notification. Once you trigger it you can update it or cancel it through this number. In the next example, you’ll find all necessary examples.
 

Example

 
We will create an example that will load an image from that smartphone gallery and add it to a newly created contact.
 
This is what our application looks like:
 

HTML

Application main page.
 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *"/>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"/>
        <title></title>

        <link href="lib/ionic/css/ionic.css" rel="stylesheet"/>
        <link href="css/style.css" rel="stylesheet"/>

        <!-- ionic/angularjs js -->
        <script src="lib/ionic/js/ionic.bundle.js"></script>

        <!-- cordova script (this will be a 404 during development) -->
        <script src="js/ng-cordova.min.js"></script>    
        <script src="cordova.js"></script>

        <!-- your app's js -->
        <script src="js/app.js"></script>
    </head>
    <body ng-app="starter">

        <ion-pane>
            <ion-header-bar class="bar-stable">
                <h1 class="title">Image Picker Example</h1>
            </ion-header-bar>
            <ion-content ng-controller="ImagePickerController">
                <button class="button button-full button-positive" ng-click="getImageSaveContact()">
                    Get Image and Save a Contact with It
                </button>
                <img ng-src="{{collection.selectedImage}}" style="width:100%; height: auto;"/>
            </ion-content>
        </ion-pane>

    </body>
</html>
 
Continue to the next page

  • Fix the title!! Gallery

  • 罗芳

    thx for your this post! And I want to show the image that anyone i selected on some view. now,i can get the results data like this( file:///data/data/com.ionicframework.ioncus549345/cache/xxxx.jpg).However, it don’t appear as excepted when i use this image file path. How should I do?

    • Could you please elaborate your problem with more details?

    • Neha Prakash

      I am facing the same problem…pls help.

  • nelaturuk

    Hi.. where can i get the download link for this sample ? I am not able to find the attachment. could you please guide me to that.

    • You can directly use my code. Or mail me and I’ll send you a github link where you can download a complete project.

      • Sushant Joshi

        I’m getting an error as follows:

        ionic.bundle.js:26794 TypeError: Cannot read property ‘getPictures’ of undefined
        at Object.getPictures (ng-cordova.js:4740)
        at Scope.$scope.getImageSaveContact (controllers.js:41)
        at fn (eval at compile (ionic.bundle.js:27638), :4:248)
        at ionic.bundle.js:65427
        at Scope.$eval (ionic.bundle.js:30395)
        at Scope.$apply (ionic.bundle.js:30495)
        at HTMLButtonElement. (ionic.bundle.js:65426)
        at defaultHandlerWrapper (ionic.bundle.js:16787)
        at HTMLButtonElement.eventHandler (ionic.bundle.js:16775)
        at triggerMouseEvent (ionic.bundle.js:2953)

        Any ideas on solving this?

  • R.O.

    Thanks for this great tutorial.
    Sir, i would like to use offline storage like PouchDB to store and retrieve images and i have been battling with it for quite some time now.
    And i would be so grateful, if you can put me through with a simple illustration.
    Many thanks.

  • Divya G

    Hi.. thanks for the tutorial. I am getting error while encoding base64. Don’t make functions within a loop. -> }); line 41 of javascript file .Any solution?

  • kazwert

    nothing happen when i clicked that button, what should i do?

    • If nothing happens then there’s probably an error, look at console log. I bet one or more Cordova plugins are missing.

      • kazwert

        wahhh fix it, sorry for my uncarefully hehe, nice tutorial Master Dragan 😀 Thanks

  • hi sir..i have emoji images as buttons ..how to attach that emoji buttons to text area

  • in ionic using angular js

  • please help me

  • yoni

    the convert to base 64 saved my ass. Thanks 🙂

  • Marita Sequiera

    i am getting an error called “Cannot read property ‘getPictures’ of undefined”. please help me! Thanks!

    • Putra Soerya

      try to debug them on real device,
      -> ionic run android

    • Edih Pere Elijah

      +1

  • Atula

    hi ! I am not getting any images and it is only selecting one image on device.

  • kazwert

    i use it and it works really good, but now when my phone os update to marshmallow, it didnt work, on console log,it says refused, any idea?

    • kazwert

      and when i call imagepicker function, my app is close

      • Edih Pere Elijah

        I tried it with imagepickerext and got same issue so +1

  • mikey

    Hi… Thanks for the tutorial. Its working for me and I am able to select 10 images using image picker plugin and show those images in my application page. Now how can I fetch all the gallery images at same time without manually selecting the images on a button click? Please help..

  • el5465

    beginner here so took some time to incorporate into my existing code but it works! thank you

  • ペガソス

    Hello, how can I display every selected image, because this only shows the last image picked.

  • Jozef

    Great tutorial!

    Is there any way to crop the image before saving it?

  • Will this deploy on an ios device utilizing the same code?

  • Sushant Joshi

    I’m getting an error as follows:

    ionic.bundle.js:26794 TypeError: Cannot read property ‘getPictures’ of undefined
    at Object.getPictures (ng-cordova.js:4740)
    at Scope.$scope.getImageSaveContact (controllers.js:41)
    at fn (eval at compile (ionic.bundle.js:27638), :4:248)
    at ionic.bundle.js:65427
    at Scope.$eval (ionic.bundle.js:30395)
    at Scope.$apply (ionic.bundle.js:30495)
    at HTMLButtonElement. (ionic.bundle.js:65426)
    at defaultHandlerWrapper (ionic.bundle.js:16787)
    at HTMLButtonElement.eventHandler (ionic.bundle.js:16775)
    at triggerMouseEvent (ionic.bundle.js:2953)

    Any ideas on solving this?

  • KB

    Hello Gajotres, thanks for the tutorial. But sadly that is not a solution to a problem I am facing right now, I wonder if it happens to you as well. I use cordova-64base-to-gallery plugin, it was working, but now it doesn’t work correctly. It looks like I don’t have permission to access the ios gallery. Then I can’t find any library about ios gallery permission, and I see you don’t any function to ask for permission before accessing the gallery. My question is, do we need explicit permission to access ios gallery?