Working with Camera in Ionic 2 and Ionic Native

photography-801891_1280Ionic Native is a set of wrappers for popular Cordova plugins, which provides you an ability to easy use native features in your hybrid mobile app. Today we’ll consider one of the most popular features – work with camera plugin.

First of all, you’ll need to install Ionic, create the new app and install camera plugin.

Ionic Native coming out of box with Ionic 2, so you don’t need anything to start use it.

By default Ionic 2 app has the tabbed interface with 3 tabs. We don’t need them, so please change app.ts to the following:

I’ve replaced

with

Now you can safely remove app/pages/about, app/pages/contact and app/pagestabs folders. After running ‘ionic serve’ your app will look like this:

Developing with Cordova Camera plugin

Now it’s time to add button and launch the Camera. First of all, we’ll modify the app/pages/home/home.html template as following:

Also modify the app/pages/home/home.ts to the following:

We have two buttons and two options – allow user to take photo using device camera or choose existing photo from the gallery. Code for both methods is exactly same, but sourceType is different (Camera.PictureSourceType.PHOTOLIBRARY or
Camera.PictureSourceType.CAMERA). Also we have two options of receiving the results – as base-64 encoded image data (Camera.DestinationType.DATA_URL) or as saved file URL (Camera.DestinationType.FILE_URI). First option can be useful for example to send image data to server.

Also you can see import of ‘DomSanitizationService‘. This allows us to display images via IMG tag. This is required, because otherwise built-in Angular 2 sanitization mechanisms will append ‘unsafe:’ to IMG SRC attribute and image will display as broken. This service prevents XSS by sanitizing values. You can read more about it here.

Now after taking picture/selecting it from the photo library, you’ll get on your device screen something like this:

Cordova Camera plugin in action

You can download the whole project code from my GitHub: Download

4 thoughts on “Working with Camera in Ionic 2 and Ionic Native”

  1. hi,

    am new to ionic, trying to implement the code but am having runtime error: Cannot find module “ionic-native”. also having issues with the ‘DomSanitizationService’ .  other errors include
    Typescript Error
    Property ‘PictureSourceType’ does not exist on type ‘typeof Camera’.

    Typescript Error
    Property ‘DestinationType’ does not exist on type ‘typeof Camera’.

    Typescript Error
    Property ‘getPicture’ does not exist on type ‘typeof Camera’.

    pls help is anything i need to do. i tried to install ionic native and it installed but same issue persist.

    pls help

Leave a Reply

Your email address will not be published. Required fields are marked *