Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image compression in image upload in angular4

Tags:

save(event: any, type, image_type) {
  this.uploadImageFlag = true;
   const fileList: FileList = event.target.files;
    if (fileList.length > 0) {
        const file: File = fileList[0]
        this.files.set('files', file, file.name)
        const reader = new FileReader();
        reader.onload = (event: any) => {
        this.url2 = event.target.result;
        this.upload = true;
        }
        reader.readAsDataURL(event.target.files[0]);

    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<input id="input"  type="file" accept="image/*" style=" width: 180px;" #files (change)="save($event)" />

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.

like image 653
Pragya Sharma Avatar asked Mar 23 '18 04:03

Pragya Sharma


People also ask

What is image in data compression?

Image compression is a process applied to a graphics file to minimize its size in bytes without degrading image quality below an acceptable threshold. By reducing the file size, more images can be stored in a given amount of disk or memory space.

How do I compress an image in react?

We can resize, compress and convert the images based on our requirements. To compress your images follow these three simple steps: Install the package using npm/yarn. Add the particular code block to your project.


1 Answers

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));

      );
    });

  }
}
like image 129
David Faure Avatar answered Sep 20 '22 12:09

David Faure