Accessing Picture from Gallery

In previous article, I've explained how to access Camera to take Picture using Ionic 2. This article I'm going to explain how to access photo gallery using ionic

Goal

  • Access Gallery & Choose Picture
  • Get Picture with Base64 String
  • Convert Base64 String to Viewable Image

Steps to follow

  1. Create New Ionic Project

    ionic start AccessGallery blank

  2. Add required Platform

    ionic cordova platform add android ionic cordova platform add ios

  3. Add cordova Camera Plugin https://github.com/apache/cordova-plugin-camera

    ionic cordova plugin add cordova-plugin-camera npm install --save @ionic-native/camera

  4. Open src/pages/home/home.html
<ion-content padding>
  <button ion-button color="primary" (click)="accessGallery()">Open Gallery</button>
  <img [src]="base64Image" *ngIf="base64Image" />
</ion-content>

Add Plugin in your app.module.ts

  1. Edit src/pages/home/home.ts
import { Component } from '@angular/core';
import { Camera } from '@ionic-native/camera';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  base64Image:any;
  constructor(public camera:Camera) {}
  accessGallery(){
    this.camera.getPicture({
      sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
      destinationType: this.camera.DestinationType.DATA_URL
    }).then((imageData) => {
      this.base64Image = 'data:image/jpeg;base64,'+imageData;
      }, (err) => {
      console.log(err);
    });
  }
}

How it Works ?

  1. import { Camera } from '@ionic-native/camera'; we're importing camera from ionic native
  2. We need to create an object for Camera in constructor

3.using this.camera object, we can access any functions inside Camera; where, this.camera.getPicture() used for accessing camera or gallery

1. You can pass options inside  `this.camera.getPicture()` such as quality, sourceType, destinationType and more Refer: [http://ionicframework.com/docs/v2/native/camera/#CameraOptions](http://ionicframework.com/docs/v2/native/camera/#CameraOptions)
  1. 'data:image/jpeg;base64,'+imageData; used for display picture from base64 String

Common mistakes

  • This won't work on browser, you must test it on simulator / real device
  • You must give a proper permission to access; (Phone Settings => Apps => your app name => Permission & Enable all required permissions)

Feel free to comment below for any issue or happiness ; p