How to get original image size (width & height) in JavaScript

Topic: JavaScript / jQuery« Prev|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.

  • <!DOCTYPE html>
  • <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.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>jQuery Get Real Image Dimensions</title>
  • <script type="text/javascript" src="http://code.jquery.com/jquery.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:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.