Ionic 5 Image Crop and Image Picker convert into base64 format using Native plugins

In many applications, we usually face some situation where we need to get Cropped images from users during form submissions. Cropped images are usually small in size and have only that part of an image which is required. Image crop behaviour should be easy to use and of course easy to implement 😛

Today we will implement Image Crop functionality in Ionic 5 Application using Angular 8 with the help of some Ionic Native and Cordova plugins.

In Ionic application, there will be an Image Picker from which a user can select a single image to crop. After Crop area selection, the cropped image will be displayed to the user with the image path converted to base64 data URL.

Also Read: Ionic 3 Share and Save Images from Application’s Assets Folder to Device.

To Achieve this functionality we are going to use three Native plugins:

Image Picker opens Gallary images for user selection. We can change options for Image selection limit and also set Height, Width, Quality of images picked.

Crop plugin takes an image path and opens an interactive selection where user can select crop are then hit Ok.

File plugin converts Cropped image’s temporary path to base64 encoded URL to show back cropped image to the user.

Let’s get started with implementation!

Version Check

@ionic/cli --version

   _             _
  (_) ___  _ __ (_) ___
  | |/ _ \| '_ \| |/ __|
  | | (_) | | | | | (__
  |_|\___/|_| |_|_|\___| CLI 6.4.1

Update to the latest version of Ionic CLI by running following NPM command:

$ npm install -g @ionic/cli

Create an Ionic Application

First, we will create a new Ionic application with a blank template using Angular framework by adding --type=angular option. Run the following command to create:

# Create a new Application
$ ionic start ionic-image-pick-and-crop blank --type=angular

# Enter Project Root
$ cd ionic-image-pick-and-crop

# Open code in VS code
$ code .

Install Native & Cordova Plugins

After successfully creating the Ionic application, we will install the required Cordova and Native plugins. To enable Image Picker and Image crop functionality, we will add three plugins.

Install required plugins by running following commands at the app's root folder

Image Picker

The image picker plugin will enable the feature to select images from device storage. It will open a tile-based image viewer to select from for cropping.

$ ionic cordova plugin add cordova-plugin-telerik-imagepicker
$ npm install @ionic-native/image-picker

 

Crop

After selecting an Image from Image picker next we will open Image cropper which provides a nice UI layout to crop images using a resizable selector box.

$ ionic cordova plugin add cordova-plugin-crop
$ npm install @ionic-native/crop

 

File

The File plugin is required by the Ionic application to access native storage disk on the device to open Images in the Image picker.

$ ionic cordova plugin add cordova-plugin-file
$ npm install @ionic-native/file

 

Import Plugins in App's Module

After installation open app.module.ts file, import plugins then add in providers array as shown below

//app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { Crop } from '@ionic-native/crop/ngx';
import { ImagePicker } from '@ionic-native/image-picker/ngx';
import { File } from '@ionic-native/file/ngx';


@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    Crop,
    ImagePicker,
    File,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Add Image Crop Functionality

Next, we will add Crop functionality in Home component which is created by default in a blank template.

In the home.page.html file, we will a button to open image picker for image selection. There will be a <img> tag to show a cropped image to the user and a loader element.

<ion-header [translucent]="true">
  <ion-toolbar color="warning">
    <ion-title>
      Ionic Image Pick & Crop
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding ion-text-center">

  <h5>Select Your Awsome Pic!</h5>

  <ion-button (click)="pickImage()">
    Pick Image
  </ion-button>

  <h5 *ngIf="croppedImagepath.length">Cropped Image</h5>

  <p *ngIf="isLoading">Loading ...</p>

  <img [src]="croppedImagepath" />


</ion-content>

In the home.page.ts file, we will add methods and explain its usage one by one in the application.

import { Component } from '@angular/core';
import { Crop, CropOptions } from '@ionic-native/crop/ngx';
import { ImagePicker, ImagePickerOptions } from '@ionic-native/image-picker/ngx';
import { File } from '@ionic-native/file/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  croppedImagepath = "";
  isLoading = false;

  imagePickerOptions: ImagePickerOptions = {
    maximumImagesCount: 1,
    quality: 50,
  };

  cropOptions: CropOptions = {
    quality: 50
  }

  constructor(
    private crop: Crop,
    private imagePicker: ImagePicker,
    private file: File
  ) { }


  pickImage() {
    this.imagePicker.getPictures(this.imagePickerOptions).then((results) => {
      for (var i = 0; i < results.length; i++) {
        this.cropImage(results[i]);
      }
    }, (err) => {
      alert(err);
    });
  }

  cropImage(imgPath) {
    this.crop.crop(imgPath, this.cropOptions)
      .then(
        newPath => {
          this.showCroppedImage(newPath.split('?')[0])
        },
        error => {
          alert('Error cropping image' + error);
        }
      );
  }

  showCroppedImage(ImagePath) {
    this.isLoading = true;
    var copyPath = ImagePath;
    var splitPath = copyPath.split('/');
    var imageName = splitPath[splitPath.length - 1];
    var filePath = ImagePath.split(imageName)[0];

    this.file.readAsDataURL(filePath, imageName).then(base64 => {
      this.croppedImagepath = base64;
      this.isLoading = false;
    }, error => {
      alert('Error in showing image' + error);
      this.isLoading = false;
    });
  }

}

In the class file, we are calling the pickImage() method which will execute the ImagePicker class function getPictures().

We can configure how images getting picker by providing options in imagePickerOptions using ImagePickerOptions interface. It provides the following configuration:

maximumImagesCount: max images to be selected

width: Max width to allow images

height: Max height to allow images

quality: Quality of images, defaults to 100

allow_video: Videos allowed?

title: the default is the message of the old plugin

message: the old plugin simply didn't have it, so passing null by default

outputType: Choose the format of the return value. Defined in ImagePicker.OutputType. Default is FILE_URI.
FILE_URI : 0, Return image file URI,
DATA_URL: 1, Return image as a base64-encoded string

disable_popover: Disable the iOS popover as seen on iPad

The success callback is calling the crop() method with cropOptions for adding configuration to cropped images. It provides the following options to configure:

quality:  Quality of cropped image 0 - 100;
targetHeight:  Height of cropped output image;
targetWidth: Width of cropped output image;

The showCroppedImage() method is showing the cropped image as a Base64 encoded string which can be saved.

Finally, we convert the cropped image path to base64 DataUrl by calling the readAsDataURL method of file service.

Conclusion: In this tutorial, we discussed How to use Image Picker and Image Cropper plugin in Ionic Angular application. Image picker plugin provides decent performance for Ionic hybrid apps but lags if you try to select more then two images. It depends on device resources. But it solves the purpose and Image cropper functionality also works awesome.

You can find source code in my GitHub Repo here.

Thanks for reading... do share your feedback

0 0 vote
Article Rating
Subscribe
Notify of
guest
6 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Ganesh
Ganesh
7 months ago

It is okay for single image, how can we do this for multiple images?

Ruan
Ruan
8 months ago

This article is out of date, and that Plugin is no Longer maintained.
Don’t use this Tutorial
https://github.com/wymsee/cordova-imagePicker/issues/267

Ionic Sucks

Füreder
Füreder
9 months ago

It crashes if I set maximumcount to more than 1

Abdullah Al
Abdullah Al
10 months ago

Dear,
Thank you for this clear post. I use it on ionic 4 and it works perfect.

thu thuat lap trinh
11 months ago

verry good