How to get image dimensions without loading using JavaScript
In this article, we are going to explore two methods to obtain image dimensions without loading them using JavaScript.
Get image dimensions using the Image() Object
To achieve this, you can leverage the Image() object in JavaScript, creating an image instance without adding it to the DOM.
<script> const getImageDimensions = (imageUrl) => { const img = new Image(); img.src = imageUrl; img.onload = () => { console.log('Width:', img.width); console.log('Height:', img.height); }; }; getImageDimensions('https://app.3schools.in/logo.png'); </script>
Explanation of the above code
- We create a new Image object.
- Then, set the image source using the provided URL.
- Use the onload event to wait for the image to load.
- Retrieve and display the image dimensions.
Fetching Metadata from image with Fetch API
Another approach involves fetching only the image metadata using the Fetch API. The example is given below.
<script> const getImageMetadata = (imageUrl) => { fetch(imageUrl) .then(response => response.blob()) .then(blob => { const img = new Image(); img.src = URL.createObjectURL(blob); img.onload = () => { const width = img.width; const height = img.height; console.log('Width:', width); console.log('Height:', height); }; }) .catch(error => console.error('Error fetching image metadata:', error)); }; getImageMetadata('https://app.3schools.in/logo.png'); </script>
Explanation
- Use the Fetch API to fetch the image.
- Convert the response to a blob using response.blob().
- Create a new Image object and set its source using URL.createObjectURL(blob).
- Wait for the image to load and retrieve its dimensions.
Conclusion
In this article, you have learned two methods to get image dimensions without loading the entire image using the Image() object and fetching metadata with the Fetch API.
save
listen
AI Answer
How to get image dimensions without loading using JavaScript
1
In this article, we are going to explore two methods to obtain image dimensions without l…
asked
Apu
1 answers
2915
In this article, we are going to explore two methods to obtain image dimensions without l…
Answer Link
answered
Apu
[1] The fetch() function with the HEAD method retrieves only the headers, not the entire image.
[2] The image size, represented by the content length, is obtained from the headers.
[3] The size is then converted to kilobytes by dividing it by 1024.