At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

Creating Responsive Image Gallery With Ionic

  • By Harikrishnan R
  • October 19, 2018
  • 1149 Views

Ionic Framework is an ultimate open source software development kit (SDK) which is highly recommended for developing hybrid mobile applications with JavaScript, CSS, HTML5 and its mostly popular among the Angular developers. Ionic mainly extends its significant importance on the look, feel and UI interactions of an app. It’s obvious that the interaction & look of an app is the significant part for any app and that is why we recommend you to re-consider Ionic as your next choice. So to keep up the good practice with Ionic, today we’re planning to give you the simple and useful guide to create image gallery with Ionic.
If you are new to ionic framework then make sure that the below things are prerequisite needed for an ionic application.

  1. Android environment (or iOS if you’re working on a MacOS).
  2. Nodejs
  3. Ionic
  4. Cordova

Let’s start from the scratch but before that make sure that your nodejs version is the latest one.

Step 1

First, let’s look into the process of updating cordova and ionic. Please note that without nodejs we can’t able to update or download the ionic framework or cordova so make sure you have installed Node.js.
Use the below command to update the current cordova version.

npm update -g cordova ionic

 

Step 2

Create a new ionic project, apply the below command to create new ionic project,

ionic start IonicImageGallery blank

 

Related: Reduce Overdraw From Your Android Application

 

Step 3

Now you can change the path of this folder using the command prompt like below,

cd IonicImageGallery

 

Step 4

Download ngCordova Archive

 
ngCordova is a collection of Angular extension which will make us with easy to build, test and deploy platform for the application. and you can use the below link to download ngCordova plugin.

http://ngcordova.com/docs/
or
https://github.com/driftyco/ng-cordova/archive/master.zip

 
After downloading it, unzip the file, and there you can find the file name called ng-cordova.min.js which you can find it in the below path,

ng-cordova-master\dist\.

 
Now just open the newly created project directory from the www/js folder and there we should copy this ng-cordova.min.js file, After that, we should paste & load the ng-cordova.min.js file from the index.html and here am adding it above the cordova.js, similarly you can add it wherever you wish.

<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>

 

Step 5

Include the android and ios platform to the image gallery application using the below commands. Note, here i have listed commands for both the platforms so try any of the commands based on the platform you use,
For Android platform:

ionic platform add android

 
For Mac OS users,

ionic platform add ios

 

Best To Read: How To Improve The Quality Of Android Apps Using Firebase Test Lab

Step 6

We need to install the cordova image picker plugin and this will help us to fetch the images from concerned gallery. Here is the link to download required plugin https://github.com/wymsee/cordova-imagePicker.git

Step 7

Now open the index.html and add the below code 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>

It’s time to initialize this controller in app.js file, don’t forget to change the angular.module line with $cordovaImagePicker service. Other side,

app.controller('ImagePickerController', function($scope, $cordovaImagePicker, $ionicPlatform) {
 
});

 
Add cordova-plugin-whitelist, incase if you are using the Codova 4.0+ then you must install this whitelist plugin. Also don’t forget to add the security meta tag to your index.html HEAD content.
Running an application without this plugin or meta tag will surely lead to get “Network Error” either it will show us network error or it will throw no security meta-tag found so make sure to install whitelist plugin and update proper security meta tags in index.html HEAD content as i mentioned below,

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

 
[contact-form-7 404 "Not Found"]

Steps To Trigger a notification

Add these below codes to trigger a notification,

$scope.getImageSaveContact = function() {       
   var options = {
       maximumImagesCount: 1,
       width: 800,
       height: 800,
       quality: 80
   };
   $cordovaImagePicker.getPictures(options).then(function (results) {
       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 necessary for the above function. Id is a number that represents your local notification. After trigger, it will automatically update the id.
Get the full sample code here and make sure your html file also has the same format like below ,

<!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>
Javascript will be below
var app = angular.module('starter', ['ionic','ngCordova']);
app.run(function($ionicPlatform) {
   $ionicPlatform.ready(function() {
       if(window.cordova && window.cordova.plugins.Keyboard) {
           cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
       }
       if(window.StatusBar) {
           StatusBar.styleDefault();
       }
   });
});
app.controller('ImagePickerController', function($scope, $cordovaImagePicker, $ionicPlatform, $cordovaContacts) {
   $scope.collection = {
       selectedImage : ''
   };
   $ionicPlatform.ready(function() {
       $scope.getImageSaveContact = function() {       
           var options = {
               maximumImagesCount: 1,
               width: 800,
               height: 800,
               quality: 80
           };
           $cordovaImagePicker.getPictures(options).then(function (results) {
               for (var i = 0; i < results.length; i++) {
                   $scope.collection.selectedImage = results[i];
                   window.plugins.Base64.encodeFile($scope.collection.selectedImage, function(base64){  
                       $scope.collection.selectedImage = base64;
                       $scope.addContact();
                   });
               }
           }, function(error) {
               console.log('Error: ' + JSON.stringify(error));
           });
       };
   });
   $scope.contact = {
       "displayName": "Test",
       "name": {
           "givenName" : "Harikrishnan",
           "familyName" : "Ram nivas",
           "formatted" : "Dragannn Gaiccc"
       },
       "nickname": 'Gajotres',
       "phoneNumbers": [
           {
               "value": "+919061002009",
               "type": "mobile"
           },
           {
               "value": "+919080035148",
               "type": "phone"
           }    
       ],
       "emails": [
           {
               "value": "hari@agiratech.com",
               "type": "home"
           }
       ],
       "addresses": [
           {
               "type": "home",
               "formatted": "Some Address",
               "streetAddress": "Some Address",
               "locality":"egmore",
               "region":"chennai",
               "postalCode":"600008",
               "country":"India"
           }
       ],
       "ims": null,
       "organizations": [
           {
               "type": "Company",
               "name": "Generali",
               "department": "IT",
               "title":"PHP Developer"
           }
       ],
       "birthday": Date("01/10/1992"),
       "note": "",
       "photos": [
           {
               "type": "base64",
               "value": $scope.collection.selectedImage
           }
       ],
       "categories": null,
       "urls": null
   }        
   $scope.addContact = function() {
       $cordovaContacts.save($scope.contact).then(function(result) {
           console.log('Contact Saved!');
       }, function(err) {
           console.log('An error has occured while saving contact data!');
       });
   };
});

Finally, its time to deploy the application and you can use the below command to do it,

ionic build android

 
Sounds great! Yeah! We’re done with creating the APK for creating image gallery on IONIC app and now, we’re all set to install the apk. Hopefully you could see the created apk in the corresponding folder as we mentioned in the below path,

IonicImageGallery\platforms\android\build\outputs\apk\android-debug.apk

 
[os-widget path=”/agiratechnologies/like-what-you-re-reading” of=”agiratechnologies”]
Liked it? Similarly learn all the mobile app development tricks from our largest blog repository and don’t forget to subscribe us to get the latest updates, tricks and lot more from diverse technologies. Besides all, Post us your valuable thoughts in the comment section. For any queries reach us via info@agiratech.com.

Harikrishnan R

Around 3 years of experience he scored intense knowledge on PHP, Laravel, Symfony, Angular & ensuring to learn the new & best methods to bring excellence in building applications. Also he has some aspiring dream to do Doctorate and the strange reason behind this will definitely leave a smile on your face! Yeah because he just loves writing his name as Dr. Harikrishnan