How to use Camera in Ionic 2 apps with Ionic Native -- Words (417)

Ionic
How to use Camera in Ionic 2 apps with Ionic Native

In this tutorial,we are going to see an example or demo app for accessing native device camera in Ionic 2 apps.

To access or integrate native device features with Ionic apps or even with pure Apache Cordova apps (and mobile web views) we can use Ionic Native which is a wrapper for Cordova plugins that provides better integration with Angular 2 and TypeScript so instead of callbacks we can use powerful promises and observables .

Before starting make sure you have Node.js and NPM installed ,and of course the Ionic framework .

Since we are using native device features ( Camera ) you need to install Cordova with

npm install -g cordova 

We need to test our app on real device ,in order to be able to build for your target platform ,Android or iOS you need to have Java SDK installed in case of Android and you need to have a MAC OS and Xcode for iOS .

So go ahead ,open up your terminal under Linux/Mac or command prompt under Windows and then scaffold a new Ionic 2 app using

ionic start ionic-native-example-camera blank --v2

Go ahead and serve the app just to make sure evrything is OK

cd ionic-native-example-camera 
ionic serve

You should be able to visit your app with the browser

Now you need to add the target platform ,in my case it's Android but you can target iOS too if you have a MAC

ionic platform add android

Next add the camera plugin with

ionic plugin add cordova-plugin-camera

Now everything is setup ,we need to add the code for accessing the native camera so open home.ts or any file where you want to add the code for taking pictures .

On the head of the file add the import instruction to import Camera from 'ionic-native'

import {Camera} from 'ionic-native';

Next inside your TypeScript class ,add a public member variable for storing image data

public image: string;

And then add the method for taking a picture

getPicture(){

    Camera.getPicture({
        destinationType: Camera.DestinationType.DATA_URL,
        targetWidth: 320,
        targetHeight: 320
    }).then((data) => {

        this.image = "data:image/jpeg;base64," + data;

    }, (error) => {

        console.log(error);
    });

}



mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.