Angular Tutorials

Angular 13 Image Upload, Preview, Crop, Zoom Example

Throughout this comprehensive tutorial, we will explain how to upload an angular image, show image preview by creating a Base64 url in angular, how to crop an image in angular, how to zoom the image, and how to scale the image in Angular.

Adding image uploading, previewing, cropping, scaling, and zooming in Angular is easy; this required feature can be created using the ngx-image-cropper plugin.

The Image cropper for Angular is available through the node package manager, and this plugin allows you to add profound features related to an image file.

Register image cropper in Angular’s main app module class, after which you can access numerous methods and API for handling file upload, preview, and zoom.

To know more about the image cropper, visit here.

Angular Image Cropper Example

  • Step 1: Set Up Angular Environment
  • Step 2: Install Bootstrap Package
  • Step 3: Add NGX Image Cropper Package
  • Step 4: Register ImageCropperModule in App Module
  • Step 5: Integrate Image Cropper in Angular
  • Step 6: Start Development Server

Set Up Angular Environment

Angular CLI is a go-to tool for angular app development, so execute the command to commence the angular command-line-interface tool installation.

npm install -g @angular/cli

Install a latest version of angular app:

ng new ng-demo-app

Use command to land on the project’s root:

cd ng-demo-app

Install Bootstrap Package

To use the custom UI components, we require to install Bootstrap package in Angular app.

Execute command to install the package:

npm install bootstrap

Include bootstrap css into angular.json file:

...
...
    "styles": [
        "src/styles.scss",
        "node_modules/bootstrap/dist/css/bootstrap.min.css"
    ],
...
...

Add NGX Image Cropper Package

Once you created a new angular app and entered into the project further, you have to install and add the image cropper plugin into the angular app:

npm install ngx-image-cropper

Register ImageCropperModule in App Module

Ideally, to access the image cropper package’s various methods and properties, you have to register the ImageCropperModule into the main app module class.

Open and insert code into the app.module.ts file:

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

import { ImageCropperModule } from 'ngx-image-cropper';

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

export class AppModule {}

Integrate Image Cropper in Angular

Implementing image cropper functionality is a facile process; so far, we have completed almost every setup.

Now, get into the TypeScript template import ImageCroppedEvent API; this will allow you to crop an uploaded image. It will convert the image file into Base64 format and show the cropped image preview.

Additionally, we added three custom functions for displaying the cropper component, starting the cropper component and showing an error message when the error occurred while uploading the file.

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.scss']
})

export class AppComponent {

    imgChangeEvt: any = '';
    cropImgPreview: any = '';

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

    imgLoad() {
        // display cropper tool
    }

    initCropper() {
        // init cropper
    }
    
    imgFailed() {
        // error msg
    }
}

Create button attach change event, similarly use image-cropper directive and load it with various events and methods to configure it for image upload, crop, and preview.

Open and place below code in app.component.html file:

<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)="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>

Start Development Server

Lastly, test the feature we built, so execute the ng serve command from the command prompt to run the development server.

ng serve

Open the url on the browser:

http://localhost:4200

Conclusion

We have completed the image cropper tutorial; in this example, we learned how to add an image cropper package in angular to upload, preview, crop, zoom, and scale an image that you can directly upload to the server.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Router DOM 6 Fetch Current URL / Pathname Tutorial

If you want to learn how to get the current route's name, component pathname or…

2 days ago

React Js Hide & Show with React Bootstrap Collapse Tutorial

React show and hide example. In this tutorial, we will show you how to step…

5 days ago

How to Integrate Tabs in React Js with React Bootstrap

Tabs are one of the best UI elements for displaying multiple contents in a single…

1 week ago

How to Build Toast Component in React Js with Bootstrap

In this tutorial, we will learn how to create a toast notification component in the…

2 weeks ago

React Js Bootstrap Modal Popup Component Tutorial

Bootstrap offers tons of custom UI solutions. On top of that, it is easy to…

2 weeks ago

React Build Counter using useReducer Hook Tutorial

React js counter using the useReducer hook example. In this post, we will learn how…

2 weeks ago