How to Get Image Dimensions in Javascript
In this tutorial, you will learn how to get image dimensions in javascript. Whenever we want to display an image, we make use of the img
element. This source of the image can be a relative URL or absolute URL.
The img
element has a bunch of useful attributes such as height and width to manipulate the dimensions of an image. The image dimensions can also be changed using CSS. The point to be noted here is that image size depends upon the extension of the image as well as its dimensions.
You may have seen websites where they restrict users to upload images only of certain dimensions. To apply those restrictions, they have to detect the image dimensions using javascript before going forward with the upload process.
The img
element has naturalHeight
and naturalWidth
properties. These properties return the actual dimensions of the image. We can take advantage of these properties to accomplish our goal.
In the following example, we have one img element and one button element. Upon click of a button, we will get the original dimensions of the image and display that on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 4 elements in the HTML file (
button
,span
,hr
, andimg
). - The
span
element is empty as of now. We will display the dimensions of the image in it using javascript. - The
button
element has“Get Size”
asinnerText
. - We are using
background.jpg
as a source of theimg
element. You can use any image of your choice. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button>Get Size</button> <span id="size"></span> <hr> <img src="background.jpg" alt="" style="height:250px; width:250px;"> <script src="script.js"></script> </body> </html>
Javascript
- We have selected
button
,img
, andspan
elements using thedocument.querySelector()
method and stored them in thebtn
,span
, andimg
variables respectively. - We have attached a
click
event listener to thebutton
element. - In the event handler function, we are getting image dimensions using the
naturalHeight
andnaturalWidth
property of theimg
element and displaying that in thespan
element using theinnerText
property.
let btn = document.querySelector('button'); let span = document.querySelector('#size'); let img = document.querySelector('img'); btn.addEventListener('click', () =>{ span.innerText = `Height: ${img.naturalHeight} - Width: ${img.naturalWidth}`; });