In Angular Upload Image, Preview & Crop with example

In this article, we’ll learn how to upload images, preview images,s and crop images in Angular. For that, we used the “ngx-image-cropper” module. Let’s create a new project to implement upload crop and scale images in angular for that you need to run the following command to create a project.


ng new image-cropper

“image-cropper” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go to their directory. For example “cd image-cropper”. To Run angular applications, it required to run “ng serve”.


After that, we need to install the ngx-image-cropper npm package in our application. For that run the below command to install.


npm install ngx-image-cropper

After installing the module, we need to put it in our “app.module.ts” file so we can use in our code. below is the code need to update in “app.module.ts” files.


import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";
import { ImageCropperModule } from "ngx-image-cropper";

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

Let’s add the below code in our app.component.ts file to upload image and preview image and scale that image.


import { Component, VERSION } from "@angular/core";

import { ImageCroppedEvent } from "ngx-image-cropper";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;

  imgChangeEvt: any = "";
  cropImgPreview: any = "";

  onFileChange(event: any): void {
    this.imgChangeEvt = event;
  }
  cropImg(e: ImageCroppedEvent) {
    this.cropImgPreview = e.base64;
  }


}

below code need to “app.component.html” file.


<div class="container mt-5 text-center">

  <h3 class="mb-5">Angular Image Crop</h3>

  <div class="col-md-12">
    <input type="file" (change)="onFileChange($event)" />
  </div>

  <div class="col-md-8">
    <image-cropper [imageChangedEvent]="imgChangeEvt" [maintainAspectRatio]="true" [aspectRatio]="4 / 4"
      [resizeToWidth]="256" format="png" (imageCropped)="cropImg($event)" (imageLoaded)="imgLoad()"
      (cropperReady)="initCropper()" (loadImageFailed)="imgFailed()">
    </image-cropper>
  </div>

  <div class="col-md-4">
    <h6>Image Preview</h6>
    <img [src]="cropImgPreview" />
  </div>

</div>



Output

Below is the full embeded code for image upload preview and crop images in angular. you can easily used in your application.
Example

Spread the love
  •  
  •  
  •  
  •  
  •  
  • 1
  •  
  •