js获取图片原始大小

js获取图片原始大小

摘要:

  浏览器中显示的图片大小未必是他真实的高和宽,比如像下面这样,我们给他加上宽和高的样式

<img src="IE.png" style="width:25px;height:25px;">

  这样在浏览器中显示的大小就是25px。那么我们如何获取图片的真实大小呢?,下面的代码就实现了这个功能

 1 <!DOCTYPE html> 2 <html> 3     <head> 4         <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 5     </head> 6     <body> 7         <img src="IE.png" id="image" style="width:25px;height:25px;">      8         <script> 9             // 设置延时保证图片加载完成10             setTimeout(function() {11                 var12                 real_width,13                 real_height,14                 _im         = document.getElementById('image'),15                 im          = document.createElement('img');16                 im.src      = _im.src,17                 real_width  = im.width,18                 real_height = im.height;19                 alert(real_width+'\n'+real_height);20             },500);21         </script>22     </body>23 </html>

注意:上面代码本人在IE7+和Chrome上都测试过了,因为没有装IE6,所以没法测试。