Vinayak Hebbar
Vinayak Hebbar

Reputation: 1

How to compress multiple image in angular? here i attached code which can compress only 1 image at a time

How to compress multiple image in angular? here i attached code which can compress only 1 image at a time help me to solve this. i dont know how to make loop for multiple images, i did not get any documentation for 'ngx-image-compress'

import {Component} from '@angular/core';
import {NgxImageCompressService} from 'ngx-image-compress';


@Component({
  selector: 'app-root',
  template: `
    <div>
      <button (click)="compressFile()">Upload and compress Image</button>
      <img *ngIf="imgResultBeforeCompress" [src]="imgResultBeforeCompress" alt="">
      <img *ngIf="imgResultAfterCompress" [src]="imgResultAfterCompress" alt="">
    </div>
  `
})
export class AppComponent {

  constructor(private imageCompress: NgxImageCompressService) {}
  
  imgResultBeforeCompress:string;
  imgResultAfterCompress:string;

  compressFile() {
  
    this.imageCompress.uploadFile().then(({image, orientation}) => {
    
      this.imgResultBeforeCompress = image;
      console.warn('Size in bytes was:', this.imageCompress.byteCount(image));
      
      this.imageCompress.compressFile(image, orientation, 50, 50).then(
        result => {
          this.imgResultAfterCompress = result;
          console.warn('Size in bytes is now:', this.imageCompress.byteCount(result));
        }
      );
      
    });
    
  }
}

Upvotes: 0

Views: 3096

Answers (2)

David Faure
David Faure

Reputation: 1376

There have been an update and now you can upload multiple files at once in ngx-image-compress using uploadMultipleFiles() method.

You can run the demo here https://stackblitz.com/edit/ngx-compress-sample

uploadMultipleFiles() {
   this.imageCompress.uploadMultipleFiles().then((multipleFiles: UploadResponse[]) => {
     console.warn(`${multipleFiles.length} files selected`);
   });
}

Upvotes: 0

moustafa
moustafa

Reputation: 271

I am not sure if I got you right, hope one of the below helps:

  • As per the documentation (https://github.com/dfa1234/ngx-image-compress#readme), it seems like you can only select one file at a time. So if you want the user to upload multiple files, go and compress the image every time the user press the button to upload and save the result in a list of images. You can loop over the list of images after that and perform whatever operations you want.

  • If you want to use this library for compression only. You can use a normal input of type file, and then when the use selects the images, run this.imageCompress.compressFile on every image to get the compressed image.

Upvotes: 1

Related Questions