How To Crop Image Before Upload In Angular

When you select any image from the file input, it will trigger fileChangeEvent. Before upload if you want to transform your image, here ngx-image-cropper is useful. Install following npm for use ngx image corper

npm i ngx-image-cropper

Add the module to your module file :

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ImageCropperModule } from 'ngx-image-cropper';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ImageCropperModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Add the element to your HTML :

<section class="m-5">
    <h3>Image Cropper Example</h3>
    <label >
        <input style="display: none;"
        #avatar
        type="file"
        (change)="uploadImage($event)"
        id="getFile"
        name="image"
        accept="image/*"
        />
        <span style="cursor: pointer; text-decoration: underline; color: blue;">Here Upload Image</span>   
    </label>
    
    <section class="w-25 h-25">
        <image-cropper
        [imageChangedEvent]="imageChangedEvent"
        [maintainAspectRatio]="true"
        [aspectRatio]="4 / 3"
        [resizeToWidth]="256"
        [cropperMinWidth]="128"
        format="png"
        (imageCropped)="imageCropped($event)"
        ></image-cropper>
        <div class="buttons pr-0">
            <button *ngIf="Image" (click)="getCroppedImage()" class="btn btn-primary">Crop & Save</button>
          </div>
    </section>
    <span class="mt-2">image :</span>
    <div class="w-25 h-25 mt-2">
        <img [src]="cropimage">
    </div>
    
</section>

And add this to your ts file :

import { Component } from '@angular/core';
import { base64ToFile, ImageCroppedEvent } from 'ngx-image-cropper';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  imageChangedEvent: any;
  croppedImage: any;
  cropimage: any;
  Image:boolean = false

  uploadImage(event: any): void {
    this.imageChangedEvent = event;
  }

  imageCropped(event: ImageCroppedEvent) {
    this.croppedImage = event.base64;
    this.Image = true;
    console.log(event, base64ToFile(event.base64));
  }

  getCroppedImage() {
    this.cropimage = this.croppedImage
  }

}

And now run your project : npm start

output :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories