Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!