Image compression in image upload in angular4

Pragya Sharma picture Pragya Sharma · Mar 23, 2018 · Viewed 12.2k times · Source

I am using the below function for uploading image and sending it to backend. The problem is the image size is quite big which takes time to reach to backend. I have seen many examples on how to compress image but I dont really want to change my existing code and revamp the module so can someone please tell me how I can change this function and compress the image.

Answer

David F. picture David F. · Jan 21, 2019

I made this library for what you need: https://www.npmjs.com/package/ngx-image-compress

You have a complete sample on the read-me page. Here a snippet if you want a idea of how you can use it:


@Component({...})
export class AppComponent {

  constructor(private imageCompress: NgxImageCompressService) {}

  compressFile() {

    this.imageCompress.uploadFile().then(({image, orientation}) => {

      console.warn('Size before:', this.imageCompress.byteCount(result));

      this.imageCompress.compressFile(image, orientation, 50, 50).then(

        result => console.warn('Size after:', this.imageCompress.byteCount(result));

      );
    });

  }
}