Access Photo Gallery using Ionic 2

access photo gallery using ionic 2
access photo gallery using ionic 2
access photo gallery using ionic 2

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 2

Goal

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

DOWNLOAD SOURCE CODE

Steps to follow

1. Create New Ionic Project

ionic start AccessGallery blank --v2

2. Add required Platform

ionic platform add android
ionic platform add ios

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

ionic plugin add cordova-plugin-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>

5. Edit src/pages/home/home.ts

import { Component } from [email protected]/core';
import { Camera } from 'ionic-native';
@Component({
 selector: 'page-home',
 templateUrl: 'home.html'
})
export class HomePage {
  base64Image
  constructor() {}
 accessGallery(){
   Camera.getPicture({
     sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
     destinationType: 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'; -> we’re importing camera from ionic native
  2. Camera.getPicture() used for get picture (camera / gallery)
    1. You can pass options inside Camera.getPicture() such as quality, sourceType, destinationType and more Refer: http://ionicframework.com/docs/v2/native/camera/#CameraOptions
  3. 'data:image/jpeg;base64,'+imageData; used for display picture from base64 String

DOWNLOAD SOURCE CODE

access photo gallery using ionic 2 Output

access-gallery-output

  • Yoga Wiranata

    Hi Sundra,
    I have tried your tutorial, I run with (ionic run browser) it’s 100% work
    but when I try to build with android it have an error..
    I try to uninstall cordova-plugin-camera, and my project can build in android
    can you see where the error come from?

    can I know your android sdk version to build it? and what used in AndroidManifest.xml?

    thank’s for your tutorial 🙂