Categories
JavaScript Answers

How to check image width and height before upload with JavaScript?

Spread the love

Sometimes, we want to check image width and height before upload with JavaScript.

In this article, we’ll look at how to check image width and height before upload with JavaScript.

How to check image width and height before upload with JavaScript?

To check image width and height before upload with JavaScript, we can get the dimensions by assigning the image data string to the src property of an img element.

For instance, we write

const reader = new FileReader();

reader.readAsDataURL(fileUpload.files[0]);
reader.onload = (e) => {
  const image = new Image();
  image.src = e.target.result;
  image.onload = (e) => {
    const height = e.target.height;
    const width = e.target.width;
    if (height > 100 || width > 100) {
      alert("Height and Width must not exceed 100px.");
      return false;
    }
    alert("Uploaded image has valid Height and Width.");
    return true;
  };
};

to create a FileReader object in the file input change event handler.

Then we call readAsDataURL with fileUpload.files[0] to read the fileUpload.files[0] selected file into a base64 string.

Then we create an img element with Image and set the base64 image URL string as the src attribute value with

image.src = e.target.result;

And then we get the width and height from e.target with

const height = e.target.height;
const width = e.target.width;

And then we can check the width and height after that.

Conclusion

To check image width and height before upload with JavaScript, we can get the dimensions by assigning the image data string to the src property of an img element.

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 *