Angular Image Cropper Example
- Step 1:Configure an Angular Environment
- Step 2: Bootstrap should be installed
- Step 3: NGX Image Cropper Package to be installed
- Step 4: ImageCropperModule should be registered in the App Module
- Step 5: Incorporate an image cropper into your Angular application
- Step 6: Launch the Development Server
Execute command to install the package:
npm install bootstrap
Add NGX Image Cropper Package
npm install ngx-image-cropper
In the App Module, add the ImageCropperModule.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ImageCropperModule } from 'ngx-image-cropper'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ReactiveFormsModule, ImageCropperModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Add code into the app.component.ts file:
import { Component } from '@angular/core'; import { ImageCroppedEvent } from 'ngx-image-cropper'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { imageChange: any = ''; cropImagePreview: any = ''; onFileChangeEvent(event: any): void { this.imageChange = event; } cropImage(e: ImageCroppedEvent) { this.cropImagePreview = e.base64; } }
Open the app.component.html file and paste the following code in it:
<div class="container mt-5 text-center"> <h3 class="mb-5">Angular Image Crop Example</h3> <div class="col-md-12"> <input type="file" (change)="onFileChangeEvent($event)" /> </div> <div class="col-md-8"> <image-cropper [imageChangedEvent]="imageChange" [maintainAspectRatio]="true" [aspectRatio]="4 / 4" [resizeToWidth]="300" format="png" (imageCropped)="cropImage($event)" > </image-cropper> </div> <div class="col-md-4"> <h6>Demonstration Image</h6> <img [src]="cropImagePreview" /> </div> </div>
Let’s now run the project with the following command.
ng serve -o