0

I am using an reactjs and I have a component for my iamge:

here is my code:

import  React from "react";
require("../../../../css/story/body/story-body.css");
export class StoryImage extends  React.Component{

render() {
    var imgHtmlElement="";
       var img = new Image();
        img.src= "https://upload.wikimedia.org/wikipedia/commons/1/1c/Aspen-PopulusTremuloides-2001-09-27.jpg";
        var height = img.height;
        var width = img.width;

        console.log("height: "+height+"width: "+width);
        imgHtmlElement=<img
            src={this.props.imgUrl!=undefined?this.props.imgUrl.desktopUri:""}
            className="img-responsive11" alt="" />

    return (
        <div>
        {imgHtmlElement}
        </div>);
}

}

What I am trying to do is to read the height and width of the image in its source before loading it to the and then decide based on its dimension.

As you see in my code I am trying ti do that with:

 var img = new Image();
        img.src= "https://upload.wikimedia.org/wikipedia/commons/1/1c/Aspen-PopulusTremuloides-2001-09-27.jpg";
        console.log(img.src);
        var height = img.height;
        var width = img.width;

        console.log("height: "+height+"width: "+width);

How ever this is all I get:

height: 0 width: 0

What is wrong with my approach? Can anyone help?

Hamed Minaee
  • 2,480
  • 4
  • 35
  • 63
  • 1
    *"read the height and width of the image in its source before loading it"* - well, yeah. You can't get the dimensions of an image that you don't have. – JJJ Jun 21 '18 at 12:49

1 Answers1

4

You have to wait for your image to load before checking its width and height.

You can use the onload attribute for that :

let img = new Image();
let height, width;
img.onload = () => {
  height = img.height;
  width = img.width;

  console.log("height: " + height + "width: " + width);
};
img.src = "https://upload.wikimedia.org/wikipedia/commons/1/1c/Aspen-PopulusTremuloides-2001-09-27.jpg";
Zenoo
  • 12,670
  • 4
  • 45
  • 69