使用js获取图片原始尺寸

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

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

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

  

复制代码 代码如下:

  <!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>

  // 设置延时保证图片加载完成

  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>

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

  非常好用的代码,本人大多数项目中都在使用,大家放心用吧