-3

I have an URL, for eg: w3schools image. When I try to read image and calculate its width and height, I'm getting null at img.src=imgData. This is the code I'm trying.Why I'm not able to read image from this URL.

var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
  $rootScope.width = this.width;
  $rootScope.height = this.height;
}
  • 1
    Possible duplicate of [How to get image size (height & width) using JavaScript?](https://stackoverflow.com/questions/623172/how-to-get-image-size-height-width-using-javascript) – Nikolaj Dam Larsen Nov 17 '17 at 07:56

2 Answers2

2

You can try clientwidth and clientheight as well .

var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
    img.src = imgData;
    img.onload = function () {
       $rootScope.width = this.clientWidth;;
       $rootScope.height = this.clientHeight;
    }
Sandip Kumar
  • 241
  • 3
  • 25
0

You can use naturalHeight and naturalWidth on the image element. Like this:

var imgData = https://www.w3schools.com/w3css/img_fjords.jpg;
img.src = imgData;
img.onload = function () {
   $rootScope.width = this.naturalWidth;
   $rootScope.height = this.naturalHeight;
}
Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45