Upload Image Aspect Ratio Of 1:1 In Angular

In this blog we are going to learn about image validation

First, open file app.component.ts and insert below code

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  filesToUpload:any;
  height:any;
  width:any;
  flag: boolean = true;
  onChange(fileInput: any) {
    const URL = window.URL || window.webkitURL;
    const Img = new Image();
    this.filesToUpload = (fileInput.target.files);
    Img.src = URL.createObjectURL(this.filesToUpload[0]);
    Img.onload = (e: any) => {
      this.height = e.path[0].height;
      this.width = e.path[0].width;
      const hwightWidth = `${this.height} and ${this.width}`
      alert(hwightWidth);
      if (this.height == this.width) {
        this.flag = true
        var reader = new FileReader()
        reader.readAsDataURL(fileInput.target.files[0])
        reader.onload = (e: any) => {
          this.filesToUpload = e.target.result;
        }
      }
      else {
        this.flag = false
      }
    }
  }
}

Than open file app.component.html and also insert below code

<div class="container">
    <input type="file" class="form-control" accept="image/*" alt="image" (change)="onChange($event)">
    <img [src]="filesToUpload" style="width: 300px;height:300px;" />
    <p *ngIf="!flag" class="text-danger">Please upload image aspect ratio of 1:1.</p>
</div>

Now run code using npm start

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories