Use js to get the original size of the image

  • 2020-03-30 04:27:10
  • OfStack

The size of the image displayed in the browser is not necessarily his true height and width, for example, we give him a width and height style as shown below

< Img SRC = "IE. PNG" style = "width: 25 px; Height: 25 px;" >

The size displayed in the browser is 25px. So how do we get the true size of the image? , the following code implements this function


 <!DOCTYPE html>
 <html>
     <head>
         <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
     </head>
     <body>
         <img src="IE.png" id="image" style="width:25px;height:25px;">    
         <script>
             //Set the delay to ensure that the picture is loaded
             setTimeout(function() {
                 var
                 real_width,
                 real_height,
                 _im         = document.getElementById('image'),
                 im          = document.createElement('img');
                 im.src      = _im.src,
                 real_width  = im.width,
                 real_height = im.height;
                 alert(real_width+'n'+real_height);
             },500);
         </script>
     </body>
 </html>

Note: the above code has been tested on both IE7+ and chrome. It cannot be tested because IE6 is not installed.

Very good to use the code, I most projects are in use, we rest assured to use it


Related articles: