Sometimes, we want to get width and height of an image with JavaScript FileReader.
In this article, we’ll look at how to get width and height of an image with JavaScript FileReader.
How to get width and height of an image with JavaScript FileReader?
To get width and height of an image with JavaScript FileReader, we use the Image constructor.
For instance, we write
<input type="file" name="profileImg" accept="image/*" class="input-file" />
to add a file input.
Then we write
const input = document.querySelector("input");
input.onchange = (event) => {
const reader = new FileReader();
reader.onload = () => {
const image = new Image();
image.src = reader.result;
image.onload = () => {
consoe.log(image.width);
};
};
const [file] = event.target.files;
reader.readAsDataURL(file);
};
to select the input with querySelector.
And then we set its onchange property to a function that creates a FileReader object.
We set its onload property to a function that gets the read file data.
In it, we create an image with the Image constructor.
And we set image.src to the read file result which is a base64 URL string.
Then image.width has the width.
We get the file from the input with event.target.files.
And we call readAsDataURL to read the file into the base64 URL.
Conclusion
To get width and height of an image with JavaScript FileReader, we use the Image constructor.