shourov_return0
shourov_return0

Reputation: 73

How to get image Height and Width while uploading image in React?

Is there any way to get Image Height and Width while uploading image...

I am trying the code below but always getting 0 0:

const uploadedImage = e.target.files[0];
var image = new Image();

image.src = uploadedImage;

console.log(image.naturalWidth,image.naturalHeight);

How Can I Solve this?

Upvotes: 1

Views: 6195

Answers (2)

James L
James L

Reputation: 11

  const [dimensions, setDimensions] = React.useState({ width: 0, height: 0 })

 const src = URL.createObjectURL(file)
<img
        src={src}
        alt={file.file.name}
        onLoad={(e: React.SyntheticEvent<HTMLImageElement>) => {
          const { naturalWidth, naturalHeight } = e.currentTarget
          setDimensions({ width: naturalWidth, height: naturalHeight })
        }}
      />

Upvotes: 1

Tanjin Alam
Tanjin Alam

Reputation: 2506

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        var objectUrl = _URL.createObjectURL(file);
        img.onload = function () {
            alert(this.width + " " + this.height);
            _URL.revokeObjectURL(objectUrl);
        };
        img.src = objectUrl;
    }
});

You may find details HERE

Upvotes: 0

Related Questions