Angular 12 Image Cropper, Resizer Example – Ngx-Image-Cropper Package Tutorial

How to Crop and Resize Images while uploading in Angular; Ngx-Image-Cropper Package Tutorial; In this Angular tutorial, we will learn how to add image cropper, resizer and calling component in Angular application. We will be using the ngx-image-cropper tool and discuss its configuration and customization properties.

This Angular post is compatible with Angular 4 upto latest versions, Angular 7, Angular 8, Angular 9, Angular 10, Angular 11 & Angular 12

Why use Cropper, Resizer, Scaling feature for Images?

Sometimes, users are requested to upload images of some specific dimensions. In that case, it becomes a cumbersome task for a user to edit images to crop, resize them in any external application and then upload. To make this expeditious, we can integrate the image cropper, resized feature in our own Angular application.

Features of Ngx Image Cropper Library

On selecting the image, the user can perform various functionalities like zoom, scale or even crop the image. At the real-time selected portion of the image is converted into the Base64 URL. This Base64 URL is used to display the preview part of the image.

  • Cropping of Images
  • Images can be resized
  • Scaling the image, by configuring the selection area.
  • It returns the Base64 URL to upload on the server.

The selected and cropped area of the image is converted into a base64 encoded string which can be easily uploaded to the server and saved as a real image into JPG or PNG formats.

 

How to add Image Cropper, Resizer Tool in Angular App?

Let’s discuss the quick steps, we are going to follow to implement Image selection and crop functionality from scratch.

  • Step 1 – Create Angular Application
  • Step 2 – Install  Ngx Image Cropper Package
  • Step 3 – Configure App Module
  • Step 4 – Adding Image Cropper Resizer Tool
  • Step 5 – Properties and Event Handlers
  • Step 6 – Serve the Application

 

Let’s get started!

Step 1 – Create an Angular Project

We will create a new Angular project using the NG CLI tool. Here we will use the current version on Ng CLI which is v8.3.15.

Run the following command in terminal to create a new Angular project:

$ ng new angular-image-uploader
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS

Step 2 – Install  Ngx Image Cropper Package

After successfully creating an Angular project, next, we will install the Angular Image Cropper package which is very easy to install and use in the project.

Here we will use the ngx-image-cropper package which very popular and loads of configurations which we will discuss with examples.

Installation

Run following NPM command in terminal to install Image Cropper package:

$ npm install ngx-image-cropper --save

Step 3 – Configure App Module

To use Image Cropper anywhere in the Angular project, we will import it in our App’s main module in app.module.ts then add in the imports array as shown below:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

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 { }

 

Step 4 – Adding Image Cropper Resizer Tool

To use image cropper in a component, simply add the following three elements in the template.

# Update HTML Template

Input : Input control of type file is required to select an image.

ImageCropper : The image-cropper component directive will display the selected image with a cropper area to select the portion of the actual image.

Img : The preview of the selected cropped image will be shown in the img element.

<div class="container">
    <div class="row" style="margin-top: 5%;">
        <div class="text-center col-md-12">
            <input type="file" (change)="fileChangeEvent($event)" />
        </div>
    </div>
    <div class="row" style="margin-top: 5%;">
        <div class="text-center col-md-8">
            <h5>Crop Image</h5>
            <image-cropper 
            [imageChangedEvent]="imageChangedEvent" 
            [maintainAspectRatio]="true" 
            [aspectRatio]="4 / 4"
            [resizeToWidth]="256" 
            format="png" 
            (imageCropped)="imageCropped($event)" 
            (imageLoaded)="imageLoaded()"
            (cropperReady)="cropperReady()" 
            (loadImageFailed)="loadImageFailed()"></image-cropper>
        </div>
        <div class="text-center col-md-4">
            <h5>Preview</h5>
            <img [src]="croppedImage" />
        </div>
    </div>
</div>
Note: We have added bootstrap.css in the index.html file to beautify the layout
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

 

# Update Class Component

In component class, import ImageCroppedEventthen define a few variables and methods as shown below:

// app.component.ts
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 {
  title = 'angular-image-uploader';

    imageChangedEvent: any = '';
    croppedImage: any = '';

    fileChangeEvent(event: any): void {
        this.imageChangedEvent = event;
    }
    imageCropped(event: ImageCroppedEvent) {
        this.croppedImage = event.base64;
    }
    imageLoaded() {
        // show cropper
    }
    cropperReady() {
        // cropper ready
    }
    loadImageFailed() {
        // show message
    }
}

Step 5 – Properties and Event Handlers

In this step, we will discuss some of the important input and output configuration properties provided by the library.

Input Properties

How to load an image by default inside image cropper?

You can use either of the below property to load the default image into the Image cropper. Ideally, these properties get the file after the image is selected or fileChangeEvent is triggered from file input control.

  • imageChangedEvent: FileEvent – The change event from your file input (set to null to reset the cropper)
  • [imageFile: Blob(File) – The file you want to change (set to null to reset the cropper)
  • imageBase64: string – If you don’t want to use a file input, you can set a base64 image directly and it will be loaded into the cropper
  • imageURL: string- If you don’t want to use a file input or a base64 you can set an URL to get the image from. If requesting an image from a different domain make sure Cross-Origin Resource Sharing (CORS) is allowed or the image will fail to load.

In our example, we used [imageChangedEvent] to get selected file Object as input to image cropper.

  • format : string; Default is png – Output format (png, jpeg, webp, bmp, ico) (not all browsers support all types, png is always supported, others are optional)
  • aspectRatio : number; Default 1 / 1 – The width / height ratio of selection box (e.g. 1 / 1 for a square, 4 / 3, 16 / 9 …)
  • resizeToWidth : The cropped image will be resized to at most this width (in px)
  • resizeToHeight : The cropped image will be resized to at most this height (in px)

Output Event Handlers

Following are the event handlers emitted by the image-cropper.

  • imageCropped – Emits an ImageCroppedEvent each time the image is cropped
  • imageLoaded – Emits the LoadedImage when it was loaded into the cropper
  • cropperReady – Emits when the cropper is ready to be interacted. The Dimensions object that is returned
  • contains the displayed image size
  • startCropImage – Emits when the component started cropping the image
  • loadImageFailed – Emits when a wrong file type was selected (only png, gif and jpg are allowed)

CSS Variable

You can add the following CSS overriding properties in the style.scss file at application root to add your own colours.

  • --cropper-outline-color – The background colour you see around the cropper
  • --cropper-overlay-color – The background colour you see around the image

 

Step 6 – Serve the Application

Now run the Angular application by hitting the following npm command in the CLI terminal

$ ng serve --open

It will open the application at the following URL.

http://localhost:4200/

Conclusion

Finally, in the Angular app, we integrated the Image cropper and Resizer tool. The image cropper tool gives a base64 URL as output. The image can be saved into any format using the base64 URL.

At the client app, image cropper adds many features including cropper, resizer and scaling the images. The ngx-image-cropper library provides many features and configuration options as we discussed above. Moreover, you can check out the official documentation.

 

 

Leave a Reply

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