Welcome folks today in this blog post we will be compressing size
of multiple images
to smaller size
in typescript using the ngx-image-compress
library. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command
ng new sampleapp
cd sampleapp
And after that you need to install the below library using the below command
npm i ngx-image-compress
And after that you will see the below directory
structure of the angular app as shown below
And now you need to go to app.component.html
file and copy paste the following code
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<header> <h1>ngx-image-compress demo</h1> </header> <hr /> <section> <button (click)="compressFile()">Upload and compress Image</button> <img *ngIf="imgResultBeforeCompress" [src]="imgResultBeforeCompress" alt="" /> <img *ngIf="imgResultAfterCompress" [src]="imgResultAfterCompress" alt="" /> </section> <hr /> |
As you can see we have the simple button to compress images
and we have attached the compressFile()
method on button click. And then we are displaying the images
before compress and after compress.
And now we need to go to app.component.ts
file and copy paste the following code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import { Component } from '@angular/core'; import { DataUrl, DOC_ORIENTATION, NgxImageCompressService, UploadResponse, } from 'ngx-image-compress'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { imgResultBeforeCompress: DataUrl = ''; imgResultAfterCompress: DataUrl = ''; imgResultUpload: DataUrl = ''; constructor(private imageCompress: NgxImageCompressService) {} compressFile() { return this.imageCompress .uploadFile() .then(({ image, orientation }: UploadResponse) => { this.imgResultBeforeCompress = image; console.warn('Size in bytes was:', this.imageCompress.byteCount(image)); this.imageCompress .compressFile(image, orientation, 50, 50) .then((result: DataUrl) => { this.imgResultAfterCompress = result; console.warn( 'Size in bytes is now:', this.imageCompress.byteCount(result) ); }); }); } uploadFile() { return this.imageCompress .uploadFile() .then(({ image, orientation }: UploadResponse) => { this.imgResultUpload = image; console.warn('DOC_ORIENTATION:', DOC_ORIENTATION[orientation]); console.warn( `${image.substring(0, 50)}... (${image.length} characters)` ); }); } } |
As you can see we are importing the ngx-image-compress
library at the top and then we are using the imageCompress()
method to upload
and compress
the multiple images.