Ionic – Camera and Photo Gallery

Ionic native camera plugin allows us to take a picture using the device camera. In this apps we will be creating two buttons, one to take the photo using device camera and other is to load existing picture from the device album.

The screenshot of our apps.

 

What we will learn:

  1. Access the Cordova camera plugin to trigger camera picture and get the image back in the Base64 or URI format.
  2. Parse the Base64 data or URI on an img tag DOM object.
  3. Display the URI if it’s in the URI format.

Step 1: ionic start MyCamera blank
Step 2:
$ ionic cordova plugin add cordova-plugin-camera
$ npm install –save @ionic-native/camera

Step 3: Add the following code in home.html.

<ion-header> ...Camera...</ion-header>
 
<ion-content padding>
  <ion-row class="center">
    <ion-col width-50>
      <button ion-button (click)="getPicture(1)">Show Camera</button>  
    </ion-col>
    <ion-col width-50>
      <button ion-button (click)="getPicture(0)">Show Album</button>  
    </ion-col>
  </ion-row>
 
  <ion-item class="no-border">
    <ion-label>Return image file URI</ion-label>
    <ion-toggle energized [(ngModel)]="useURI"></ion-toggle>
  </ion-item>
   
  <ion-card>
    <img [src]="imageData" *ngIf="imageData" />
    <ion-card-content>
      <ion-card-title>
        <div *ngIf="useURI">
          Using URI
        </div>
        <div *ngIf="!useURI">
          Using Base64
        </div>
      </ion-card-title>
      <p *ngIf="useURI">
        Your URI is {{ imageData }}
      </p>
      <p *ngIf="!useURI">
        Your Base64 image has {{ (imageData + '').length }} bytes
      </p>
    </ion-card-content>
  </ion-card>
</ion-content>

Once we load or capture a photo, we can use ion-toggle to display on/off of image url.

Step 4: Add the following code in home.ts

import { Component, Input } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Camera } from '@ionic-native/camera';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public imageData: string;
  @Input('useURI') useURI: Boolean = true;
   
  constructor(public navCtrl: NavController, private camera: Camera) {
  }
   
  getPicture(sourceType){
    this.camera.getPicture({
        quality: 50,
        allowEdit: true,
        encodingType: this.camera.EncodingType.JPEG,
        saveToPhotoAlbum: false,
        destinationType: this.useURI ? this.camera.DestinationType.FILE_URI : this.camera.DestinationType.DATA_URL,
        targetWidth: 800,
        targetHeight: 800,
        sourceType: sourceType
    }).then((imageData) => {
        if (this.useURI) {
          this.imageData = imageData;
        } else {
          this.imageData = "data:image/jpeg;base64," + imageData;
        }
    }, (err) => {
        console.log(err);
    });
  }  
}