Get Image Dimension In Angular 2
Solution 1:
With the Angular2 approach, I'll create a custom directive to get the height and width of any element. For img, I'll apply it(directive) in the img tag and whenever I want to get the height & width of an img, I just need click it. You can modify according to your need.
DEMO : https://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview
directive.ts
import { Directive,Input,Output,ElementRef,Renderer} from'@angular/core';
@Directive({
  selector:"[getHeightWidth]",
  host:{
    '(click)':"show()"
  }
})
exportclassGetEleDirective{ 
  constructor(private el:ElementRef){
  }
  show(){
    console.log(this.el.nativeElement);
    console.log('height---' + this.el.nativeElement.offsetHeight);
    console.log('width---' + this.el.nativeElement.offsetWidth);   
  }
}
app.ts
@Component({
  selector: 'my-app',
  template: `
  <div style="width:200px;height:300px">
       <img getHeightWidth                 <!-- here I'm using getHeightWidth directive-->
            [src]="source" alt="Angular2" 
            width="100%" 
            height="100%">  
   </div>
  `,
})
export class AppComponent {
  source='images/angular.png';
}
Solution 2:
I created function to get image size
getImgSize(imageSrc: string): Observable<ISize> {
    let mapLoadedImage = (event): ISize => {
        return {
            width: event.target.width,
            height: event.target.height
        };
    }
    var image = newImage();
    let $loadedImg = fromEvent(image, "load").pipe(take(1), map(mapLoadedImage));
    // Rxjs 4 - let $loadedImg = Observable.fromEvent(image, "load").take(1).map(mapLoadedImage);
    image.src = imageSrc;
    return $loadedImg;
}
interface ISize { width: number; height: number; }
Also you can subscribe on load event in html
<img (load)="loadedImg($event)" [src]="imageSrc"> and get size from it.
Solution 3:
In case if you need to get the image size in ts file:
getImageDimension(image): Observable<any> {
    returnnewObservable(observer => {
        const img = newImage();
        img.onload = function (event) {
            constloadedImage: any = event.currentTarget;
            image.width = loadedImage.width;
            image.height = loadedImage.height;
            observer.next(image);
            observer.complete();
        }
        img.src = image.url;
    });
}
Call above method:
const image = {
  url: 'https://kalgudi.com/store/assets/images/e-mahila1.jpg',
  context: 'Mahila self help group'
}
this.getImageDimension(image).subscribe(
   response => { 
     console.log(response);
   }
);
Solution 4:
Simply you can use following code to get the width and height (Resolution) of the Image.
HTML Code
<img #pic [src]="imgURL" (load)="onLoad()>In Angular
@ViewChild('pic', { static: false }) pic: ElementRef;
onLoad() {
   console.log((this.pic.nativeElementasHTMLImageElement).naturalWidth);
   console.log((this.pic.nativeElementasHTMLImageElement).naturalHeight);
 }
Solution 5:
In component.ts
this.uploadService.validateandUploadFile(files, 300, 300);
In service.ts file
import { Injectable } from '@angular/core';
import * as AWS from 'aws-sdk/global';
import * as S3 from 'aws-sdk/clients/s3';
import { BehaviorSubject } from 'rxjs';
  FOLDER = '/';
    
    imageUrl = "";
    
    resData: BehaviorSubject<any> = new BehaviorSubject(null);
    
    data = { message: "", data: "" };
    
    constructor() { }
    validateandUploadFile(file, Iheight, Iwidth) {
    
        let fileToUpload = file;
        if (fileToUpload.type == "image/jpeg" || fileToUpload.type == "image/png" || fileToUpload.type == "image/jpeg") {
            //Show image preview
            let reader = new FileReader();
            reader.onload = (event: any) => {
                var img = new Image();
                img.onload = () => {
                    let width = img.width;
    
                    let height = img.height;
                    if (width <= Iwidth && height <= Iheight) {
                        this.imageUrl = event.target.result;
    
                        this.uploadfile(file);
                    } else {
    
                        this.data.message = "You can maximum upload " + Iheight + " * " + Iwidth + " File";
                        this.data.data = "";
                        this.resData.next(this.data);
                        returnthis.resData;
                    }
                };
    
                img.src = event.target.result;
            }
            reader.readAsDataURL(fileToUpload);
        } else {
            this.data.message = "You can't be able to upload file except JPG and PNG format";
            this.data.data = "";
            this.resData.next(this.data);
            returnthis.resData;
        }
    }
uploadfile(file) {
    if (file != null) {
        const bucket = new S3(
            {
                accessKeyId: '***********************',
                secretAccessKey: '**********************************',
                region: 'us-east-2'
            }
        );
        const params = {
            Bucket: '*********',
            Key: file.name,
            Body: file,
            ACL: 'public-read'
        };
        var that = this;
        bucket.upload(params, function (err, data) {
            if (err) {
                console.log('There was an error uploading your file: ', err);
                returnfalse;
            }
            console.log('Successfully uploaded file.', data);
            that.data.message = "Successfully uploaded file.";
            that.data.data = data.Location;
            that.resData.next(that.data);
            return that.resData;
        });
    }
}
Post a Comment for "Get Image Dimension In Angular 2"