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 behavior should be easy to use and of course easy to implement 😛
Today we will implement Image Crop functionality in Ionic 4 Application using Angular 7 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 dataUrl.
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!
Create Ionic 4 Application
Make sure you have latest Ionic CLI version installed
1 2 | $ npm install -g ionic |
Create a new Ionic 4 application with a blank template by running following command
1 2 3 4 5 6 7 8 9 | # Create a new Application $ ionic start Ionic4ImageCrop blank # Enter Project Root $ cd Ionic4ImageCrop # Open code in VS code $ code . |
Install Native & Cordova Plugins
Install required plugins by running following commands at the app’s root folder
Image Picker
1 2 3 | $ ionic cordova plugin add cordova-plugin-telerik-imagepicker $ npm install @ionic-native/image-picker |
Crop
1 2 3 | $ ionic cordova plugin add cordova-plugin-crop $ npm install @ionic-native/crop |
File
1 2 3 | $ 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | //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 an <img> tag to show a cropped image to the user and a loader element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <ion-header> <ion-toolbar color="primary"> <ion-title> Ionic 4 Select & Crop Image </ion-title> </ion-toolbar> </ion-header> <ion-content padding text-center> <ion-button (click)="pickImage()"> Pick Image to Crop </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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | //home.page.ts import { Component } from '@angular/core'; import { Crop } from '@ionic-native/crop/ngx'; import { ImagePicker } 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 = { maximumImagesCount: 1, 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, { quality: 50 }) .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; }); } } |
On button click pickImage() method is called, which use imagePicker service to call getPictures method. In imagePickerOptions we are passing ImagePicker options.
After image selection, the cropImage method will be called to pass a cropped image path to other method showCroppedImage.
Finally, we convert the cropped image path to base64 DataUrl by calling the readAsDataURL method of file service.
verry good
Dear,
Thank you for this clear post. I use it on ionic 4 and it works perfect.
It crashes if I set maximumcount to more than 1
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
It is okay for single image, how can we do this for multiple images?