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

Issue

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!!

Solution

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.

Answered By – MortenMoulder

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published