1

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?

2 Answers 2

1
  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 })
        }}
      />
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for posting this answer. While this code may answer the question, might you please edit your post to add an explanation as to why/how it works? This can help future readers learn and apply your answer. You are also more likely to get positive feedback (upvotes) when you include an explanation.
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.