---
title: "JavaScript获取图片的原始尺寸"
author: "zhouyrt"
date: "2016-04-20T10:30:00Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2016-04-20T10:30:00Z"
id: 2292509
url: "https://snandy.iteye.com/blog/2292509"
---

页面里的img元素，想要获取它的原始尺寸，以宽度为例可能首先想到的就是width，如下

```
<img src="http://img11.360buyimg.com/da/g14/M07/01/0E/rBEhVlNhh8wIAAAAAADmFBLo1twAAM26gOmCgYAAOYs716.jpg">
<script>
    var img = document.getElementsByTagName('img')[0]
    var width = getWH(img, 'width') // 690
</script>
```

这里使用的getWH方法是[之前文章](http://www.cnblogs.com/snandy/archive/2011/09/06/2167440.html)里提到的。这时候获取的宽度和图片的原始尺寸是一样的。

 

如果给img加上了width属性，这种方式就不行了，比如图片实际宽度是690，设置了width为400，这时按上面的方式获取则返回400

```
<img width="400" src="http://img11.360buyimg.com/da/g14/M07/01/0E/rBEhVlNhh8wIAAAAAADmFBLo1twAAM26gOmCgYAAOYs716.jpg">
<script>
    var img = document.getElementsByTagName('img')[0]
    var width = getWH(img, 'width') // 400
</script>
```

很明显，400不是图片的原始宽度。

 

有一种方式可以获取到，直接创建一个新img对象，然后把旧img的src赋值给新的，这时候获取新img的宽度即可

```
<img width="400" src="http://img11.360buyimg.com/da/g14/M07/01/0E/rBEhVlNhh8wIAAAAAADmFBLo1twAAM26gOmCgYAAOYs716.jpg">
<script>
function getNaturalWidth(img) {
    var image = new Image()
    image.src = img.src
    var naturalWidth = image.width
    return naturalWidth
}
var img = document.getElementsByTagName('img')[0]
getNaturalWidth(img) // 690
</script>
```

需要注意的是，这里新创建的image是不需要添加的DOM文档里的。

 

HTML5提供了一个新属性[naturalWidth](http://www.w3.org/TR/2011/WD-html5-author-20110705/the-img-element.html#dom-img-naturalwidth)/[naturalHeight](http://www.w3.org/TR/2011/WD-html5-author-20110705/the-img-element.html#dom-img-naturalheight)可以直接获取图片的原始宽高。这两个属性在Firefox/Chrome/Safari/Opera及IE9里已经实现。改造下获取图片尺寸的方法。

```
function getImgNaturalDimensions(img, callback) {
    var nWidth, nHeight
    if (img.naturalWidth) { // 现代浏览器
        nWidth = img.naturalWidth
        nHeight = img.naturalHeight
    } else { // IE6/7/8
        var imgae = new Image()
        image.src = img.src
        image.onload = function() {
            callback(image.width, image.height)
        }
    }
    return [nWidth, nHeight]
}
```

注意IE6/7/8的处理，创建了一个新的img，仅设置其src，这时需要让[图片完全载入](http://www.cnblogs.com/snandy/p/3704938.html)后才可以获取其宽高。因此这里是异步的，可以传一个回调，回调里把原始的宽高作为参数传入。

 

相关：

[http://www.cnblogs.com/snandy/p/3704938.html](http://www.cnblogs.com/snandy/p/3704938.html)

[http://www.sitepoint.com/html5-responsive-design-image-dimensions/](http://www.sitepoint.com/html5-responsive-design-image-dimensions/%20) 

[http://www.w3.org/TR/2011/WD-html5-author-20110705/the-img-element.html#the-img-element](http://www.w3.org/TR/2011/WD-html5-author-20110705/the-img-element.html#the-img-element%20)