Sometimes, we want to check a selected image’s width and height selected with a file input with JavaScript.
In this article, we’ll look at how to check a selected image’s width and height with JavaScript.
Use the FileReader and Image Constructors
We can use the FileReader
constructor to create an object to read the file.
Then we can use the Image
constructor to create an image with the read file as the content.
For instance, if we have the following file input:
<input type='file'>
Then we can read the file into an image by writing:
const fileUpload = document.querySelector('input')
const reader = new FileReader();
fileUpload.addEventListener('change', () => {
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = (e) => {
const image = new Image();
image.src = e.target.result;
image.onload = () => {
const {
height,
width
} = image;
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;
};
};
})
We select the file input with document.querySelector
.
Then we create a FileReader
instance.
And then we add a change event listener to the file input with addEventListener
.
In the event listener, we call reader.readAsDataURL
to read the file.
The file is stored in fileUpload.files
object.
Index 0 has the first file selected.
Then we set the reader.onload
property to a function that creates the Image
instance.
We set image.src
to e.target.result
to set the read file as the content of the img
element created.
Then we set the image.onload
property to a function that gets the width
and height
of the image.
And we check the width
and height
to be what we want with the if
statements.
Now if we select an image file, we should see the alert boxes pop up depending on the size of the image.
Conclusion
We can use the FileReader
constructor to create an object to read the file.
Then we can use the Image
constructor to create an image with the read file as the content to check the width and height of an image file selected.