How to Pick and Crop Image in Ionic 6 Angular App

Uploading an image is a usual task that almost all of us do every day, whether it is a social media platform or any other important file that needs to be uploaded.

When users select an image to upload, in that case, most of the time, users not aware of the dimension of the selected or picked image.

In ionic, we are creating a standard functionality through which you can add image picker and image crop feature in the Ionic app using native and Cordova packages.

Throughout this tutorial, you will find out the simple way of how to add an image picker and how to crop the selected image from the device storage in the Ionic angular app using Ionic native and Cordova image picker not only but also crop plugins.

Ionic 6 Angular Image Cropper Integration Example

  • Step 1: Install Ionic App
  • Step 2: Install Ionic Native and Cordova Plugins
  • Step 3: Register Dependencies in Ionic
  • Step 4: Add Image Cropper in Ionic Angular App
  • Step 5: Start Application

Install Ionic App

Before you begin adding image cropper in Ionic, ensure you have Ionic CLI set up on your system:

npm install -g @ionic/cli

After installing Ionic CLI, begin installing the Ionic Angular application:

ionic start ionic-image-cropper-example blank --type=angular

Thereafter, enter inside the application:

cd ionic-image-cropper-example

Remove Type Errors

You have to remove strict type errors make sure to set “strictTemplates”: false in angularCompilerOptions in tsconfig.json file.

Install Ionic Native and Cordova Plugins

Open terminal, execute following commands to install imagepicker, Ionic native core, crop and file plugins:

ionic cordova plugin add cordova-plugin-telerik-imagepicker

npm install @ionic-native/image-picker

npm i @ionic-native/core

Then, run command to install the crop and file plugins which allows cropping the image files:

ionic cordova plugin add cordova-plugin-crop

npm install @ionic-native/crop

This plugin fulfills a File API allowing read/write access to files residing on the device. Likewise, the File class executes static convenience functions to access files and directories.

ionic cordova plugin add cordova-plugin-file

npm install @ionic-native/file

Register Dependencies in Ionic

In this step, you require to add ionic native and Cordova plugins into the app.module.ts file:

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';


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


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

export class AppModule {}

Add Image Cropper in Ionic Angular App

Use an ion-button to add a button that allows users to choose images from the ionic app and add the chooseImg()method, which triggers and lets the user select the image files from system storage.

Add code in home.module.html:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Image Cropper in Ionic Example
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-grid>
    <ion-row>
      <ion-col text-center>
        <ion-button (click)="chooseImg()">Choose Image</ion-button>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>

        <h5 *ngIf="convertBase64.length">File</h5>

        <p *ngIf="loading">Loading ...</p>
      
        <img [src]="convertBase64" />

      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

To crop the image, use file API’s readAsDataURL method, which converts the file to base64; you can also adjust the image quality and number of images to be picked in one go.

Add code in home.module.ts:

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


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

export class HomePage {

  convertBase64 = "";
  loading = false;

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

  cropOpt: CropOptions = {
    quality: 58
  }

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


  chooseImg() {
    this.imagePicker.getPictures(this.imagePickerOptions).then((res) => {
      for (var i = 0; i < res.length; i++) {
        this.imageCropOpt(res[i]);
      }
    }, (error) => {
      alert(error);
    });
  }

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

  imgCrop(file) {
    this.loading = true;
    var urlCopy = file;
    var splitFilePath = urlCopy.split('/');
    var nameImage = splitFilePath[splitFilePath.length - 1];
    var urlFile = file.split(nameImage)[0];

    this.file.readAsDataURL(urlFile, nameImage).then(base64 => {
      this.convertBase64 = base64;
      this.loading = false;
    }, error => {
      alert(error);
      this.loading = false;
    });
  }

}

Start Application

Open console and run command to add any platform in which you want to test the application.

# iOS
ionic cordova platform add ios

# Android
ionic cordova platform add android

# Windows
ionic cordova platform add windows

Next, run command to create a runnable build:

# iOS
ionic cordova build ios

# Android
ionic cordova build android

# Windows
ionic cordova build windows

Type any one command in the terminal to run the application:

# iOS
ionic cordova run ios -l

# Android
ionic cordova run android -l

# Windows
ionic cordova run windows -l

Ionic Image Crop

Conclusion

We have eventually completed the Ionic Angular image cropper example.

In this example, you have seen step by step instructions to implement image cropper and image picker in ionic application with the help of ionic native and Cordova libraries.