The Official Ionic Blog

Build amazing native and progressive web apps with HTML5

In past posts in this series, we looked at some of the basics of creating an Ionic App, including a basic Hello World App, an app with pages and navigation, and finally an app that calls an API.

In this article, we will look at using Ionic Native to interface with the Cordova Camera plugin. We’ll use the native camera to take a picture and output that picture into our view.

Ionic Start

We’ll start by creating an app with the blank template using ionic start.

ionic start cameraApp blank --v2 --ts

As described in the first post of this series, we now have some basic plumbing, including a home page.

Default File Structure

Setting up the Plugin

If you have not yet installed Cordova, you’ll need to do that before completing this tutorial. This may require adding sudo before the command.

npm install -g cordova

After changing into our app directory (cd cameraApp), you’ll want to add a platform for your app.

ionic platform add android

Add the camera plugin.

ionic plugin add cordova-plugin-camera

Taking a Picture

In our home.ts file, we’ll need to import Camera from ionic-native.

import {Camera} from 'ionic-native';

Inside of our HomePage class, we’ll want to create a property that will hold the base64 string of our picture.

import {Page} from 'ionic-angular';
import {Camera} from 'ionic-native';

@Page({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  public base64Image: string;

  constructor() {}
}

Now, let’s add a method,’ takePicture, which calls the Camera.getPicture method. This method accepts an options parameter and returns a promise that resolves when we get an image from the user. In our options array, we are specifying that we want our image to be a base64Image (destinationType) and that we want it to be 1000 by 1000 pixels. In the resolved promise, we are receiving imageData, which is our base64 image data.

import {Page} from 'ionic-angular';
import {Camera} from 'ionic-native';

@Page({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  public base64Image: string;

  constructor() {

  }

  takePicture(){
    Camera.getPicture({
        destinationType: Camera.DestinationType.DATA_URL,
        targetWidth: 1000,
        targetHeight: 1000
    }).then((imageData) => {
      // imageData is a base64 encoded string
        this.base64Image = "data:image/jpeg;base64," + imageData;
    }, (err) => {
        console.log(err);
    });
  }
}

UPDATE: A previous version of this post discussed using ngZone due to a bug in an earlier version of the framework. This is no longer required in the newest version of the framework.

Inside of our template, we’ll add a button that calls our takePicture method and shows an image if we have image data in our base64Image property.

<ion-navbar *navbar>
  <ion-title>
    Home
  </ion-title>
</ion-navbar>

<ion-content class="home">
  <ion-card>
    <ion-card-content>
      Hello World, this is my camera app

      <button (click)="takePicture()">Take a Picture</button>

      Latest Picture:
      <img [src]="base64Image" *ngIf="base64Image" />
    </ion-card-content>
  </ion-card>
</ion-content>

Ionic Upload

In previous parts of this series, we would normally run ionic serve here. However, in this case, because we’re working with Cordova plugins, we will need to run it on a device. ionic upload allows us to view and rapidly develop the app in the Ionic View app.

Before we run this, let’s make sure that inside our gulpfile, we’re running the build task before we upload. I added this task in the Ionic hooks section.

gulp.task('serve:before', ['watch']);
gulp.task('emulate:before', ['build']);
gulp.task('deploy:before', ['build']);
gulp.task('build:before', ['build']);
gulp.task('upload:before', ['build']); //Build before we upload

Now, we can build and upload our app to ionic.io:

ionic upload

ionic upload output

Now, we can go into Ionic View, Sync To Latest, and View our App.

ionic view

Once in our app, we can take a picture of a cute kitten and an awesome sticker by pressing the “Take a Picture” button.

taking a picture using the camera

And our awesome picture will be outputted to our view:

outputted picture

Conclusion

In under ten minutes, we have integrated a common native feature into our app with a relatively small amount of code. The combination of Ionic Native and Ionic View is a killer partnership for rapid prototyping, developing, and ultimately creating top-of-the-line mobile apps.

  • http://www.raymondcamdencom/ Raymond Camden

    I was curious why you used base64 instead of the file system, but when I saw you were using the Ionic View app, it made sense. You may want to call that out for folks who don’t read comments. It is a bit distracting but a good reminder about the kind of issue you may run into w/ Ionic View. (And to be clear, I don’t mean to imply that diminishes the usefulness of Ionic View, but you definitely don’t want to forget the limitations.)

    • http://www.mcgivery.com/ Andrew McGivery

      This was mostly just to show an example of what you can do with it… base64 could also be useful if you wanted to send the image to a server.

      • http://www.raymondcamdencom/ Raymond Camden

        Not any more useful than a raw file you can send with XHR2 or FileTransfer.

        (And yes – I know I’m debating something that isn’t necessarily important to the post – sorry! ๐Ÿ™‚

        • http://www.mcgivery.com/ Andrew McGivery

          haha. No problem Ray. Always enjoy your discussion. ๐Ÿ™‚

          I can’t really debate with you on this one cause I agree that those are viable options for sure. Only issue I could see with XHR2 would be older versions of Android (4.3 and 4.4) may not have the best support.

          Again, I was just using base64 as a quick and easy example, but I agree that the file system would also be valid. ๐Ÿ™‚

  • https://blog.nraboy.com/ Nic Raboy

    Good post. I wrote one very similar here:

    https://www.thepolyglotdeveloper.com/2016/04/use-the-device-camera-in-an-ionic-2-android-and-ios-app/

    This is beyond where I’m going though. I had a long discussion with Max Lynch on Twitter regarding NgZone seen here:

    https://twitter.com/nraboy/status/720621570859765760

    He claims that you shouldn’t have to do this, but I agree with Andrew that this is a requirement.

    • http://www.mcgivery.com/ Andrew McGivery

      So, the version of the framework that I based this post on (beta 4) had a bug that made ngZone needed to get this to work. In the newest version of the framework (beta 6), this is fixed and zones are no longer required. The post has been updated to reflect this.

      • minhnd

        How about in the 2.0.0 rc 2 version. I can not show image in ios platform ( android is fine ).

        • minhnd

          I discovered it is error with ios 10 not because of ionic framework (it worked ok with ios 9 ). So how can i fix it now ?

  • Andreas Kuhlmann

    I am wondering why the this.zone.run(…) stuff is still necessary? I though all intention of โ€˜ionic-nativeโ€™ was to smoothly integrate the cordova plugins into ionic/angular2โ€ฆ? Are there any other obstacles to be aware of?

    • https://blog.nraboy.com/ Nic Raboy

      I share the same concern as you. I was told you don’t need it, but can’t get things to work without it. To be specific, binding things with the UI.

      • http://www.mcgivery.com/ Andrew McGivery

        Should all be good now with the newest version of the framework.

    • http://www.mcgivery.com/ Andrew McGivery

      So, the version of the framework that I based this post on (beta 4) had a bug that made ngZone needed to get this to work. In the newest version of the framework (beta 6), this is fixed and zones are no longer required. The post has been updated to reflect this.

      • Andreas Kuhlmann

        Great news!
        Many thanks to the IONIC team!!!

  • yingshaoxo

    Can you support python3?

  • awebdeveloper

    why doesn’t this work with web. Cordova supports desktop na

  • Josh Garwood

    Hey @andrewmcgivery:disqus I am such a huge fan of your tutorials here; they’ve helped me greatly as I’m ramping up on Ionic2/Angular2. One issue that I ran into today though, was that the Camera app doesn’t seem to work inside of the IonicView app. Though I feel like I may be doing something wrong…

    Camera.getPicture(options).then((img) => { // do cool stuff },
    (err) => { console.log(‘There was an error: ‘ + JSON.stringify(err)); });

    I have an error handler that outputs a the error object, but it’s empty… the output is just: “There was an error: {}”

    If I generate an actual apk and install that on my phone it works like a charm. Am I missing something? I’m using ionic2 Beta8 and the latest version of the ionicView app.

  • Marcelo

    Do you know how to take a square picture ?

    • Kushal Atreya

      Camera.getPicture().then(function(imageURI) {
      console.log(imageURI);
      $scope.lastPhoto = imageURI;
      }, function(err) {
      console.err(err);
      }, {
      quality: 75,
      targetWidth: 320,
      targetHeight: 320,
      saveToPhotoAlbum: false
      });

      };

  • coder

    Not sure what am I doing wrong but nothing happens when I click “take a picture” button. Did my plugin not installed correctly or I need to give special permission somewhere in my android phone

    • Kushal Atreya

      maybe because of plugins.

  • Albert Higgins

    amazing! you just made my day ๐Ÿ™‚

  • Felipe Constantino

    Hi. How can I upload the picture to a PHP Server?

  • tuwebservices

    How can I agree my own watermark (app watermark) when I take a picture,

  • Adir Zoari

    hey andrew,
    i’m trying to display the photo after i take it but it’s not working at all.
    i wrote in
    ts file
    this.notePicture = “data:image/jpeg;base64,” + imageData;

    in html file

    it display me error photo and show this error
    “Failed to load resource: net::ERR_FILE_NOT_FOUND”

    • Vivek Gautam

      in html do this.

  • http://www.phonegappro.com Sundara Vel

    Thanks for your article. I’ve also wrote some articles about ionic 2 camera
    Access Gallery: https://phonegappro.com/ionic2-tutorial/access-photo-gallery-using-ionic-2/
    Access Camera: https://phonegappro.com/ionic2-tutorial/access-camera-using-ionic-2/

  • minhnd

    Hello I have just started with ionic 2. I followed this tutorial and it worked fine with Android. However in the ios platform, the image did not show to the view – just a blank square in the screen. This is my version info. Please help me .
    Cordova CLI: 6.4.0
    Ionic Framework Version: 2.0.0-rc.2
    Ionic CLI Version: 2.1.4
    Ionic App Lib Version: 2.1.2
    Ionic App Scripts Version: 0.0.39
    OS: Windows 7 SP1
    Node Version: v4.5.0

    • minhnd

      I discovered it is error with ios 10 not because of ionic framework (it worked ok with ios 9 ). So how can i fix it now? Is there any solutions?

      • snakelecaps

        Hey, i was crazy 30mn to show this fuckin image on ios and i just read your post… did you found any solution? Thks a lot

  • Juv Chan

    I am following the post above to create the camera app but I am getting the error below.
    The system, framework & modules version are as shown.
    Please kindly give me some guide on this, thanks very much.

    https://uploads.disquscdn.com/images/189ccbad45bf856c3272b4e3254b93f70b3b791c5598831caac292d5974aea0d.png

  • Rohan Gupta

    can we also access the properties of the clicked image like (name of image, type of image and location of image)???

  • Felipe EstradaMEJ

    Hello, i doing just what the post says but i end up with the app restarting its self and going back to the rootview.

    Any idea of how to work this out.

    I am using
    Ionic Framework 2.0.0-rc.5
    Cli version 2.2.1
    ionic App Lib 2.2.0
    Ionic App Script 1.0.0
    Cordova Cli 6.4
    node 6.9.4

    Thanks

  • Alex Devoid

    Does anybody know why I would get “Camera.getPicture: source type 1 not available.” and “No camera available” when I run this code on my ios simulator with xcode?

  • madthew83

    Guys does anyone of you know a good js library that allow me to make the image in black and white and compress it further before to upload it as base64?

  • iriekun

    hi! the image is not shown even I use any help?

  • Arul MaNo Adaptive

    in my phone this code not working as open camera why?