Share and Learn To Write Code!

Programming articles, which help you to build your application. If something you are stuck to code and complete the program, just find here your question-related articles.

Share with   

How to compress or crop image using ngx-image-cropper module in Angular javascript framework

Here we are going to see how we can crop image and reduce size of that image using ngx-image-cropper to compress image for upload low size image. We are use this using ngb model popup by opening model and select image and crop image to the rest api or firebase or AWS any server.
image operation   angular   javascript   image cropper  

Image Cropper and Compressor


We need image upload program code for upload image for gallery view or anything that time its help to what we are selecting image from the local storage i.e. my computer. We are going to make this using angular 8 java script framework. So here we are upload image by cropping and compressing image for storing small size image for optimization.


Prerequisite

  1. Node JS. To install node js please click here.
  2. Angular CLI to install angular cli in your system follow this article.
  3. Bootstrap 4. to install bootstrap click here.
  4. Install @ng-bootstrap/ng-bootstrap package. If you don't know how to use ng-bootstrap please check this article.


Example for image cropper and compressor


1) Create Angular App. If you dont know how to start with angular. Follow this article How to install angular 8 in windows operating system.


2) Install Bootstrap 4 using this article How to install bootstrap 4 in angular 9 | 8 | 7 | 6 | 5 | 4


3) Install Ng-Bootstrap in angular app using this article How to install @ng-bootstrap to angular cli and uses of @ng-bootstrap


4) Here we are going to use ngb model popup to open model and select image and crop to save the image. If you dont know the ngb model popup follow this article to use ngb model popup.


5) Install ngx image cropper package

npm i ngx-image-cropper --save


6) Add ngx-image-cropper package module to app module

// src > app > 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 {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { ImageCropperModule } from 'ngx-image-cropper';

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


7) Now add model in html component and under model body add the image cropper component


// src > app > app.component.html

<div class="container">
 <br>
 <button class="btn btn-lg btn-outline-primary" (click)="open(content)">Add New Image</button>
 <ng-template #content let-modal>
  <div class="modal-header">
   <h4 class="modal-title" id="modal-basic-title">Edit Image</h4>
   <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
   </button>
  </div>
  <div class="modal-body">
   <input type="file" accept="image/*" (change)="fileChangeEvent($event)" />
   <image-cropper [imageChangedEvent]="imageChangedEvent" [maintainAspectRatio]="true" [aspectRatio]="1 / 1"
    [resizeToWidth]="500" [resizeToHeight]="500" format="jpeg" (imageCropped)="imageCropped($event)">
   </image-cropper>
  </div>
  <div class="modal-footer">
   <button type="button" class="btn btn-primary" (click)="addImages()" *ngIf="imageselect">Save</button>
   <button type="button" class="btn btn-outline-dark" (click)="modal.close('Close click')">Close</button>
  </div>
 </ng-template>
</div>
<br>
<div class="container">
 <div class="row">
  <div class="col-lg-4 col-md-4 col-sm-12" *ngFor="let data of imagesList; let i = index">
   <img [src]="data.imagefile" alt="image" width="350" height="350">
  </div>
 </div>
</div>


8) Add type script code for model services and image cropping services


// src > app > app.component.ts

import { Component, OnInit } from "@angular/core";
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { ImageCroppedEvent } from 'ngx-image-cropper';

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

  closeResult: string;
  constructor(private modalService: NgbModal) { }

  open(content) {
    this.modalService.open(content, { ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }

  imageChangedEvent: any = '';
  imagename: File;
  image: File;
  imageselect : boolean;
  imageUrl = "";

  fileChangeEvent(event: any): void {
    this.imageChangedEvent = event;
    this.imagename = event.target.files[0];
    this.imageselect = false;
  }

  imageCropped(event: ImageCroppedEvent) {
    this.imageUrl = event.base64;
    const imageBlob = this.dataURItoBlob(this.imageUrl);
    this.image = new File([imageBlob], this.imagename.name, { type: 'image/jpeg' });
    this.imageselect = true;
  }

  dataURItoBlob(dataURI) {
    const binary = atob(dataURI.split(',')[1]);
    const array = [];
    for (let i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    return new Blob(
      [new Uint8Array(array)],
      {
        type: 'image/png',
      },
    );
  }

  imagesList: any[] = [];
  addImages() {
    var data = {
      imagefile: this.imageUrl
    };
    this.imagesList.push(data);
    this.modalService.dismissAll();
    
    // This is example for sending file to server using rest api

    // const formData = new FormData()
    // formData.append("imagefile", this.image);
    // this._service.addImage(formData).subscribe(res => {
    //   this.itemPhotos.push(data);
    //   this.modalService.dismissAll();
    // });
  }
}


On this typescript program we are used model service for open and close ngb model popup so the open(content) method is used for open model popup and perform operation.

getDismissReason(reason: any) method is used for model popup operation if someone close popup then this method execute the program.


After this we are used image cropper for this we used ImageCroppedEvent to crop and resize image.

fileChangeEvent method is used for perform the file output to get selected image and send to perform crop operation below image will show you how this work


0replies
Leave a reply
46
Registerd Users
87
Total Subscribers
59
Total Articles
38921
Total Views