Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Use The Device Camera In An Ionic 2 Android And iOS App

TwitterFacebookRedditLinkedInHacker News

As I continue to port my Ionic Framework tutorials to Ionic 2, I figured it was time to discuss how to make use of the device camera within an application. There are often needs to obtain pictures within an application. Maybe you’re creating an application like Imgur, or maybe you just want to be able to obtain a profile picture. Like I mentioned, I had written a camera tutorial a few years back on how to use the camera in an Ionic Framework application.

This time around we’re going to see how to snap pictures within an Ionic 2 Android and iOS mobile application.

Let’s start by creating a fresh Ionic 2 project. From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following commands:

ionic start CameraProject blank --v2
cd CameraProject
ionic platform add ios
ionic platform add android

A few things to note above. We are creating an Ionic 2 TypeScript project. This means that you need to have the appropriate Ionic CLI installed. If you are not using a Mac then you cannot add and build for the iOS platform.

To use the Android and iOS device camera there are a few options. Both options require the Apache Cordova camera plugin. You can use vanilla JavaScript with the plugin or you can use Ionic Native.

We’re going to use Ionic Native, but first let’s install the Apache Cordova plugin:

ionic plugin add cordova-plugin-camera

Let me start by saying that as of now, April 2016, the official Ionic Native documentation for the camera plugin is terrible. To learn how to use this plugin I had to dig into the source code. I’m going to save you the trouble.

UPDATE: The documentation as of July 2016 has improved for the camera module. In any scenario, this article will continue to put you on the correct path.

Developing the Ionic 2 Device Camera Logic

The logic file won’t be too complicated. Essentially we’ll be creating a function that uses Camera class with various options. There are some catches though which we’ll see. First open the project’s app/pages/home/home.ts file and include the following code:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Camera} from "ionic-native";

@Component({
    templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

    public base64Image: string;

    constructor(private navController: NavController) {
        this.base64Image = "https://placehold.it/150x150";
    }

    public takePicture() {
        Camera.getPicture({
            quality : 75,
            destinationType : Camera.DestinationType.DATA_URL,
            sourceType : Camera.PictureSourceType.CAMERA,
            allowEdit : true,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 300,
            targetHeight: 300,
            saveToPhotoAlbum: false
        }).then(imageData => {
            this.base64Image = "data:image/jpeg;base64," + imageData;
        }, error => {
            console.log("ERROR -> " + JSON.stringify(error));
        });
    }

}

Let’s break everything down because I’m sure some of it won’t make sense.

The first import that didn’t ship with our blank template is as follows:

import {Camera} from 'ionic-native';

This allows us to use some Angular friendly camera functionality with Ionic Native.

With the imports out of the way we find ourselves in the constructor method:

constructor(private navController: NavController) {
    this.base64Image = "https://placehold.it/150x150";
}

In the constructor we are defining a placeholder image to be used when no camera image exists.

Like I said previously, the takePicture function just calls the Ionic Native camera class and passes it a bunch of options that I dug out of the Ionic source code.

Finally you see this:

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

This is how we are refreshing the base64Image variable that is bound to the UI. This will replace the placeholder image with the data from our camera. Since the camera data is in base64 format we must declare it as such when we store it, otherwise the HTML tag won’t know what to do.

The logic at this point is done.

Designing the Ionic 2 UI

With the logic out of the way, let’s cook up a simple UI. Essentially we’re only going to have a placeholder image and navigation button on the screen. Open the project’s app/pages/home/home.html file and include the following code:

<ion-header>
    <ion-navbar>
        <ion-title>
            Ionic 2 Camera
        </ion-title>
        <ion-buttons end>
            <button (click)="takePicture()">
                <ion-icon name="camera"></ion-icon>
            </button>
        </ion-buttons>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <img src="{{ base64Image }}" />
</ion-content>

The navigation button will be of a camera and appear on the right side. The placeholder image will exist until a camera photo is taken.

This application will probably not work in an iOS simulator or web browser. iOS simulators have issues when it comes to the device camera, and since this uses native platform code, the web browser won’t understand it.

Conclusion

You just saw how to create a simple application that will take pictures and display them on the screen. Things are a little different than the Ionic Framework 1 camera tutorial that I wrote in the sense that we are now using Angular with TypeScript. Nothing was particularly difficult and it should put you on the right track towards using the device camera within your mobile application.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.