Using Smartphone Camera With Ionic Framework

Written by on July 24, 2015

Using Smartphone Camera With Ionic Framework

Example

This is what our application looks like:

HTML

Application main page.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <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"/>
        
        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.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-content ng-controller="MainCtrl" padding="true">
                <img ng-src="{{srcImage || 'img/dummy.jpg'}}" id="srcImage" width="250 " height="250" style="display: block; margin: 0 auto;"/><br/>
                
                <button class="button button-full button-positive " ng-click="takeImage() ">Take Image</button><br/>
                
                <div class="list ">
                    <label class="item item-input">
                        <span class="input-label">First Name:</span>
                        <input type="text" name="name" value="John"/>
                    </label>
                    <label class="item item-input">
                        <span class="input-label">Last Name:</span>
                        <input type="text" name="name" value="Doe"/>
                    </label>            
                    <label class="item item-input">
                        <span class="input-label">Age:</span>
                        <input type="text" name="birth" value="01.01.1988"/>
                    </label>
                </div>
            </ion-content>
        </ion-pane>
        
    </body>
</html>

JavaScript

Application JavaScript file.

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('starter', ['ionic', 'ngCordova'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
});

app.controller('MainCtrl', function($scope, $cordovaCamera) {
    $scope.takeImage = function() {
        var options = {
            quality: 80,
            destinationType: Camera.DestinationType.DATA_URL,
            sourceType: Camera.PictureSourceType.CAMERA,
            allowEdit: true,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 250,
            targetHeight: 250,
            popoverOptions: CameraPopoverOptions,
            saveToPhotoAlbum: false
        };
        
        $cordovaCamera.getPicture(options).then(function(imageData) {
            $scope.srcImage = "data:image/jpeg;base64," + imageData;
        }, function(err) {
            // error
        });
    }
});

Application Screenshot

Final application looks like this:

Deployment

Next step, we need to build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

When this step ends, look at the output log, last two lines should look something like this:

Built the following apk(s):
    D:\Development\IonicCameraDemo\platforms\android\build\outputs\apk\android-debug.apk

We’ll use the last line location to deploy our application. Make sure your smartphone is prepared to accept an incoming application. In case of Android platform, you must enable Developer Options and USB Debugging.

Do this:

adb install -r platforms\android\build\outputs\apk\android-debug.apk

Warning: If plugin fails to acquire an image on Android device consider downgrading Cordova Camera Plugin, version 0.3.5 should work just fine.

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



Categories

15 thoughts on “Using Smartphone Camera With Ionic Framework”

  1. Hi! Thanks for the tutorial. I have an issue, I do everything, but when I click on the button, nothing happen. Do you know what i´m doing wrong? Greetings!

  2. Olá!
    Fiz da forma como está descrito, mas na hora de carregar a foto ele retorna o seguinte erro: Refused to load the image ‘data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0P…KQ0hik+lNzkUnr9acP8KAGkGk9qU0lACE4FNz3pzdDTB/SmCHdqb60tIaAEP1pn+etOptIZ//Z’ because it violates the following Content Security Policy directive: “default-src *”. Note that ‘img-src’ was not explicitly set, so ‘default-src’ is used as a fallback.

    Gostaria de saber o que pode estar errado no código.
    Grato pela Atenção!

Leave a Reply