Home>

You want to upload images in an angular application,Do i want to limit the size of the uploaded image on the front end before the image is uploaded?The ng2-img-max module is exactly what i want! The ng2-img-max module uses web sorkers for image size calculations.And resides in the main thread.

Let's take a look at his use:

installation

First, install the module using npm or yarn:

$npm install ng2-img-max blueimp-canvas-to-blob --save
#or yarn:
$yarn add ng2-img-max blueimp-canvas-to-blob

blueimp-canvas-to-blob is a polyfill so thatcanvas.toblob () can be used on browsers such as safari and older versions of internet explorer.

Include polyfill scripts in your project. If you use angular cli, you can add scripts to it.angular-cli.json file:

//:.angular-cli.json
...
"scripts":[
 "../node_modules/blueimp-canvas-to-blob/js/canvas-to-blob.min.js"
],//...

After adding the script to the angular cli configuration, you will need to restart the local service.

Now we import the module into the application module or function module:

//:app.module.ts
//...
import {ng2imgmaxmodule} from "ng2-img-max";
@ngmodule ({
 declarations:[appcomponent], imports:[
  //...
  ng2imgmaxmodule
 ], providers:[], bootstrap:[appcomponent]
})
export class appmodule {}

Finally, the ng2-img-max service can be imported and injected into such a component:

import {component} from "@ angular/core";
import {ng2imgmaxservice} from "ng2-img-max";
@component ({...})
export class appcomponent {
 constructor (private ng2imgmax:ng2imgmaxservice) {}
}

use

We add a file input box to the component's template,like this:

<input type="file" (change)="onimagechange ($event)" accept="image/*" />

Add the method onimagechange in the component class, it will limit the width and height of the image to:400px, 300px:

updateimage:blob;
constructor (private ng2imgmax:ng2imgmaxservice) {}
onimagechange (event) {
 let image=event.target.files [0];
 this.ng2imgmax.resizeimage (image, 400,300) .subscribe (result =>{
  this.uploadimage=result;
 }, error =>{
  console.log ("error:", error);
 })
}

If you have multiple images that need to be resized at once,Please use the resize method instead and pass the image file array as the first parameter.

The result is a blob type, but if needed,It can be converted to the correct file using the file constructor:

//:app.component.ts
uploadedimage:file;
constructor (private ng2imgmax:ng2imgmaxservice) {}
onimagechange (event) {
 let image=event.target.files [0];
 this.ng2imgmax.resizeimage (image, 400,300) .subscribe (result =>{
  this.uploadedimage=new file ([result], result.name);
 }, error =>{
  console.log ("error", error);
 })
}

You can now upload files to your backend. Don't forget to do validation on the backend,Because the content here will prevent some users from uploading oversized or non-image files directly to the backend.

Limit only width or height

Let's say i want to limit the height to 300px and adjust the width accordingly,To keep the aspect ratio the same. Just set any threshold to 10000:

//...
onimagechange (event) {
 let image=event.target.files [0];
 this.ng2imgmax.resizeimage (image, 10000,300) .subscribe (result =>{
  this.uploadedimage=new file ([result], result.name);
 }, error =>{
  console.log ("error:", error);
 });
}

Compression instead of resizing

You can also perform lossy compression using the compress or compressimage methods,Instead of resizing the image. Just pass the maximum value (megabytes). You obviously want to run some tests,See how far i want to go for hours,While keeping the image look good.

In the following example,We limit the generated image to about 75kb:

onimagechange (event) {
 let image=event.target.files [0];
 this.ng2imgmax.compressimage (image, 0.075) .subscribe (
  result =>{
   this.uploadedimage=new file ([result], result.name);
   this.getimagepreview (this.uploadedimage);
  },  error =>{
   console.log ("😢oh no!", error);
  }
 );
}

Picture Preview

You may want to preview the images i want to upload to your users. You can do this using a filereader object. You also need to use angular's domsanitizer to make it trust the base64-encoded data uri created using the filereader object:

Now, our component content looks like this.An interesting new method in the component is getimagepreview:

//:app.component.ts
import {component} from "@ angular/core";
import {ng2imgmaxservice} from "ng2-img-max";
import {domsanitizer} from "@ angular/platform-browser";
@component ({...})
export class appcomponent {
 uploadedimage:file;
 imagepreview:string;
 constructor (
  private ng2imgmax:ng2imgmaxservice,  public sanitizer:domsanitizer
 ) {}
 onimagechange (event) {
  let image=event.target.files [0];
  this.ng2imgmax.resizeimage (image, 10000, 375) .subscribe (
   result =>{
    this.uploadedimage=new file ([result], result.name);
    this.getimagepreview (this.uploadedimage);
   },   error =>{
    console.log ("😢oh no!", error);
   }
  );
 }
 getimagepreview (file:file) {
  const reader:filereader=new filereader ();
  reader.readasdataurl (file);
  reader.onload=() =>{
   this.imagepreview=reader.result;
  };
 }
}

In our template,We can use sanitizer to display images such as:

//:app.component.html
<img
  * ngif="imagepreview"
  [src]="sanitizer.bypasssecuritytrusturl (imagepreview)">

That's all there is to it! You can also check out the ng2-img-tools package of the same author for more browser-side image processing (such as cropping).

Trends