Categories
JavaScript Answers

How to Get the Width and Height of an Image with File Reader?

Spread the love

Sometimes, we want to get the width and height of an image with file reader.

In this article, we’ll look at how to get the width and height of an image with file reader.

Get the Width and Height of an Image with File Reader

To get the width and height of an image with file reader, we can create a new img element object with the Image constructor.

For instance, we can write:

<input type='file'>

to add the file input.

Then we write:

const reader = new FileReader();
reader.onload = (theFile) => {
  const image = new Image();
  image.src = theFile.target.result;
  image.onload = () => {
    console.log(image.width, image.height);
  };
};

const input = document.querySelector('input')
input.addEventListener('change', e => {
  const [file] = e.target.files
  reader.readAsDataURL(file);
})

We create a new FileReader instance and assign it to reader .

Then we set reader.onload to a function that creates a new Image instance.

Next, we set the src property of the Image instance to theFile.target.result , which has the result that’s read from the readAsDataURL method.

Then we set the image.onload property to a function that gets the width and height of the image.

After that, we get the input with document.querySelector .

And then we call addEventListener on it to add a change event listener.

In the event handler, we get the file object from e.target.files via destructuring.

Finally, we call reader.readAsDataURL with file to read the selected file to get the size.

Conclusion

To get the width and height of an image with file reader, we can create a new img element object with the Image constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *