Ionic 5 Image Cropper and Image Picker Integration Tutorial

Last updated on by Digamber

Ionic 5 Angular Image Crop tutorial; In this quick tutorial, you will learn how to integrate image cropper, similarly image picker and convert selected image into Base64 format to resize the image in the ionic application using the Cordova and native plugins.

We are surrounded by innumerable application in which we upload images daily, and it could be you social media post, profile registration, creating an image gallery. Most of the times, users don’t know about the image size that they are uploading. In this extensive example, we will create an image crop feature in the Ionic app, due to which the user can adjust the size of the image after upload.

To build this functionality, we will take the help of Cordova Telerik ionic-native Image Picker, Crop and File packages; these plugins allow adding image picker and image cropper, which offers tons of options to customize and resize the image. Most importantly, you can pick multiple images from device storage using these plugins and adjust the height and width by considering the base64 format; nevertheless, we primarily focus on implementing image cropper in the Ionic app.

How to Add Image Cropper in Ionic 5 Angular App

  • Step 1: Create Ionic Project
  • Step 2: Add Image Picker, File and Crop Plugins
  • Step 3: Update Cordova and Ionic Native Modules
  • Step 4: Integrate Image Cropper in Ionic
  • Step 5: Test App

Create Ionic Project

At the beginning ensure you have laid down the foundation of Ionic development, apparently it could be done by installing Ionic CLI tool

npm install -g @ionic/cli

Type the command to create a new blank Ionic Angular project:

ionic start ionic-demo-app blank --type=angular

Get into the project root:

cd ionic-demo-app

Add Image Picker, Crop and File Plugins

Head over to your terminal screen, plus type all the given below commands to install Image Picker, Crop and File Cordova and Ionic native plugins.

Run command to install the plugins.

ionic cordova plugin add cordova-plugin-telerik-imagepicker

npm install @ionic-native/image-picker

Next, use commands to install crop plugin, It helps in Crop the images in Ionic.

ionic cordova plugin add cordova-plugin-crop

npm install @ionic-native/crop

Further, execute commands to add file plugin, It helps in Crop the images in Ionic.

ionic cordova plugin add cordova-plugin-file

npm install @ionic-native/file

This plugin offers a File API allowing read/write access to files dwelling on the device. Additionally, The File class provides static convenience functions to locate files and directories.

Update Cordova and Ionic Native Modules

Subsequently, head over to app.module.ts file, import ImagePicker, Crop and File modules plus inject them into the providers array.

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

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

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

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


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

export class AppModule {}

Integrate Image Cropper in Ionic

The pickerOptions sets up the options for image picker; it comes with so many options that easily set limits to image width, height, quality, message, title, output type not only but also allow_video.

Open and update home.module.ts file:

import { Component } from '@angular/core';

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


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

export class HomePage {

  croppedImgUrl = "";
  loading = false;

  pickerOptions: ImagePickerOptions = {
    maximumImagesCount: 1,
    quality: 55,
  };

  cropOpt: CropOptions = {
    quality: 55
  }

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


  selectImage() {
    this.imagePicker.getPictures(this.pickerOptions).then((results) => {
      for (var i = 0; i < results.length; i++) {
        this.imageCropMethod(results[i]);
      }
    }, (error) => {
      alert(error);
    });
  }

  imageCropMethod(pathImage) {
    this.crop.crop(pathImage, this.cropOpt)
      .then(
        newPath => {
          this.croppedImg(newPath.split('?')[0])
        },
        error => {
          alert('Error in cropper' + error);
        }
      );
  }

  croppedImg(pathImage) {
    this.loading = true;
    var copyUrl = pathImage;
    var splitPath = copyUrl.split('/');
    var imgName = splitPath[splitPath.length - 1];
    var fileUrl = pathImage.split(imgName)[0];

    this.file.readAsDataURL(fileUrl, imgName).then(base64 => {
      this.croppedImgUrl = base64;
      this.loading = false;
    }, error => {
      alert(error);
      this.loading = false;
    });
  }


}

To invoke the crop feature in ionic, add a button, add the custom method with the click event, it will open the image picker for selecting the images from the storage. The image HTML tag displays the cropped image along with a preloader UI component.

Paste the code in home.module.html file:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic Image Cropper and Picker Demo  
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-grid>
    <ion-row>
      <ion-col text-center>
        <ion-button (click)="selectImage()">Select Images</ion-button>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <h4 *ngIf="croppedImgUrl.length">Cropped File</h4>

        <p *ngIf="loading">Loading ...</p>
      
        <img [src]="croppedImgUrl" />
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

Test Application

In this final step, we will tell you how to add platforms and create build and test the app.

Consequently, you need to run anyone command to add the platform:

# iOS
ionic cordova platform add ios

# Android
ionic cordova platform add android

# Windows
ionic cordova platform add windows

In this step, again type any of the command to create the build. Plus, you may also connect your device using the USB and test the demo app.

# iOS
ionic cordova build ios

# Android
ionic cordova build android

# Windows
ionic cordova build windows

Lastly run an of the command to start the application; you may also debug this app on the Chrome browser.

# iOS
ionic cordova run ios -l

# Android
ionic cordova run android -l

# Windows
ionic cordova run windows -l

Image Cropping in Ionic

Conclusion

In this Ionic 5 image cropper example, we, bit by bit, explained how to add image cropper in ionic using Cordova and native plugins. Now, you are fully aware of how to crop an image in the ionic, angular app; moreover, we shared how to pick an image and resize its dimension and convert it to base64 format.