How to get original image size (width & height) in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the HTML5 naturalWidth
and naturalHeight
You can easily find the original or intrinsic width and heigh of an image using the HTML5 image naturalWidth
and naturalHeight
properties.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Find Real Image Width and Height</title>
<script type="text/javascript">
function imgSize(){
var myImg = document.querySelector("#sky");
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
alert("Original width=" + realWidth + ", " + "Original height=" + realHeight);
}
</script>
</head>
<body>
<img src="sky.jpg" id="sky" width="250" alt="Cloudy Sky" contextmenu="skymenu">
<p><button type="button" onclick="imgSize();">Get Original Image Size</button></p>
</body>
</html>
This method will not work in older version of Internet Explorer.
Cross Browser Solution
To avoid any cross-browser problem you can use the following method that requires jQuery.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Get Real Image Dimensions</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
var img = $("#sky");
// Create dummy image to get real width and height
$("<img>").attr("src", $(img).attr("src")).load(function(){
var realWidth = this.width;
var realHeight = this.height;
alert("Original width=" + realWidth + ", " + "Original height=" + realHeight);
});
});
});
</script>
</head>
<body>
<img src="sky.jpg" id="sky" width="250" alt="Cloudy Sky" contextmenu="skymenu">
<p><button type="button">Get Original Image Size</button></p>
</body>
</html>
Related FAQ
Here are some more FAQ related to this topic:
- How to get current image size in JavaScript
- How to increase and decrease image size using JavaScript