How to use ImagePicker to select an image from the device gallery


#1

Hello i’m new to ionic 2 and i’m doing a simple app that selects the image from the device gallery and sets it as profile picture. I read a lot about but I could not find a guideline on how to do this.
First of all I installed the following plugin

cordova plugin add https://github.com/Telerik-Verified-Plugins/ImagePicker.git

Then I read that on android I have access permissions to access the device gallery for API level >= 23; so I added it to my home.ts file:

  1. install this plugin for android permission -> cordova plugin add cordova-plugin-android-permissions

  2. include code

...
import { ImagePicker } from '@ionic-native/image-picker';
declare var cordova: any;
...
export class HomePage {
  permissions = cordova.plugins.permissions;
  
  ionViewDidLoad() {
    this.permissions.requestPermission(this.permissions.READ_EXTERNAL_STORAGE, success, error);
    function error() {
      console.warn('read external storage permission is not turned on');
    }
    function success(status) {
      if(!status.hasPermission) error();
    }
  }

  onSelectPhoto() {
    let options = {
      maximumImagesCount: 1,
      width: 100,
      heigth: 100,
      quality: 75
    }

    this.imagePicker.getPictures(options)
                    .then((results) => {
                      let base64Image = results;
                    }, (err) => { 
                      console.log('error') });
  }
}
  1. in my home.html
<div class="image">
		<a href="" (tap)="onSelectPhoto()">
			<div class="add-photo">
				<ion-icon class="camera" name="camera-outline"></ion-icon>
				<span>Add your photo</span>
			</div>
		</a>
		<div>
			<ion-item>
				<ion-avatar item-start>
					<img [src]="base64Image" *ngIf="base64Image" />
				</ion-avatar>
			</ion-item>
		</div>
	</div>

But I can not understand if the code works and still I have a runtime error -> Uncaught (in promise): ReferenceError: cordova is not defined.


#2

Ionic-native has an android-permissions plugin. I would use that, which means you can get rid of all the cordova. business. I would also suggest that you never type the word “function” inside the body of one; this will save you from many frustrating execution context bugs. Finally, if all you want is one image, I would suggest ditching the ImagePicker plugin altogether in favor of the Camera one. I found ImagePicker extremely buggy.