Home > other >  Getting the height and width of an image in Angular using TypeScript
Getting the height and width of an image in Angular using TypeScript

Time:11-18

I'm trying to get the width and height of an image using its src URL.
This code outputs "undefinedxundefined" to the console.
This is what I have now:

  getImageSize(image: string) {
let width;
let height;
let img = new Image();
img.src = image;
img.onload = function (event) {
  let targetImg = event.currentTarget as HTMLImageElement;
  width = targetImg.width;
  height = targetImg.height
}
return width   "x"   height;

}

I'm using Angular version 12.2.11.
Thanks!!

CodePudding user response:

You need to look into Observable and subscriptions:

getImageSize(url: string): Observable<any> {
  return new Observable(observer => {
    var image = new Image();
    image.src = url;

    image.onload = (e: any) => {
      var height = e.path[0].height;
      var width = e.path[0].width;

      observer.next(width   'x'   height);
      observer.complete();
    };
  });
}

Then you can subscribe to that observable and get the response from it:

this.getImageSize('your image url').subscribe(response => {
  console.log(response);
});

and that will return the width 'x' height.

CodePudding user response:

To get the rect of any HTML element use:

const el = document.getElementById('dd');
const rect = el.getBoundingClientRect();
const height = rect.height;
const width = rect.width;
  • Related