Compress image and send it to an API in Angular

Vijay Choudhary
The Startup
Published in
4 min readOct 11, 2019

Many a time it happens that an API does not accept an image that is more than 4MB and we end up getting a “Bad Request” error. It also happens with Azure custom vision( do not accept image greater than 4MB). Therefore, no worries now; here is your host who will teach you how to compress an image in angular before sending it to an API. So, to make your request work fine and make your compression easy and simplified stay tuned with the below article…………

  1. Install the library via standard npm command:

npm i ngx-image-compress

2. Import the NgxImageCompressService into your Angular module:

import {NgxImageCompressService} from 'ngx-image-compress';@NgModule({declarations: [
...
],
imports: [
...
],
providers: [NgxImageCompressService],...})export class AppModule { }

3. Create an image-compress component

ng g c image-compress

4. image-compress.component.html

<input type="file" accept=".jpg,.png,.jpeg" id="image-input" (change)="selectFile($event)"><br><br> Original: Size: {{sizeOfOriginalImage | number : '1.2-2'}}MB<br><img [src]="localUrl" height="200px"><br><br><br> Compressed: Size: {{sizeOFCompressedImage | number : '1.2-2'}}MB<br><img [src]="localCompressedURl" height="150px">

5. image-compress.component.ts

import { Component, OnInit } from '@angular/core';
import { NgxImageCompressService } from 'ngx-image-compress';
@Component({
selector: 'app-image-compress',
templateUrl: './image-compress.component.html',
styleUrls: ['./image-compress.component.scss']
})
export class ImageCompressComponent implements OnInit {constructor(private imageCompress: NgxImageCompressService) { }file: any;
localUrl: any;
localCompressedURl:any;
sizeOfOriginalImage:number;
sizeOFCompressedImage:number;
selectFile(event: any) {
var fileName : any;
this.file = event.target.files[0];
fileName = this.file['name'];
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.localUrl = event.target.result;
this.compressFile(this.localUrl,fileName)
}
reader.readAsDataURL(event.target.files[0]);
}
}
imgResultBeforeCompress:string;
imgResultAfterCompress:string;
compressFile(image,fileName) {
var orientation = -1;
this.sizeOfOriginalImage = this.imageCompress.byteCount(image)/(1024*1024);
console.warn('Size in bytes is now:', this.sizeOfOriginalImage);
this.imageCompress.compressFile(image, orientation, 50, 50).then(
result => {
this.imgResultAfterCompress = result;
this.localCompressedURl = result;
this.sizeOFCompressedImage = this.imageCompress.byteCount(result)/(1024*1024)
console.warn('Size in bytes after compression:', this.sizeOFCompressedImage);// create file from byte
const imageName = fileName;
// call method that creates a blob from dataUri
const imageBlob = this.dataURItoBlob(this.imgResultAfterCompress.split(',')[1]);
//imageFile created below is the new compressed file which can be send to API in form dataconst imageFile = new File([result], imageName, { type: 'image/jpeg' });
});}
dataURItoBlob(dataURI) {
const byteString = window.atob(dataURI);
const arrayBuffer = new ArrayBuffer(byteString.length);
const int8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
int8Array[i] = byteString.charCodeAt(i);
}
const blob = new Blob([int8Array], { type: 'image/jpeg' });
return blob;
}
ngOnInit() {
}
}

6. app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ImageCompressComponent } from './image-compress/image-compress.component';
const routes: Routes = [
{path:'home',component:ImageCompressComponent},
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', redirectTo: 'home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes,{useHash:true})],
exports: [RouterModule]
})
export class AppRoutingModule { }

7. app.component.html

<router-outlet></router-outlet>

8. Results:-

image compressed from ~6MB to ~0.4MB

Conclusion

For more details clone project from my git hub Click Here

Thank you for being tuned with me till the end……………… Happy coding ;)

--

--