javascript 获取图片原始尺寸

javascript 获取图片原始尺寸

 1 function getImgInfo(url){
 2         var img = new Image(), loaded = false;
 3         var info = {};
 4         //对于预加载的情况,即没有把图片插入DOM树
 5         img.onload = function(){
 6             img.onload = null;
 7             loaded = true;  //标志当前已加载过,防止complete再运行
 8             info['width'] = img.width;
 9             info['height'] = img.height;
10         }
11         img.src = url;
12         var orignInfo;
13         //已经加载过的图片
14         if(img.complete && !loaded){
15             //safari,firefox,chrome,与opera10+中,有两个便捷的属性
16             if(img.naturalWidth && img.naturalHeight){
17                 info['width'] = img.naturalWidth;
18                 info['height'] = img.naturalHeight;
19             }else if(img.runtimeStyle){
20                 //IE runtimeStyle不用同步style就能重绘原来的元素
21                 orignInfo = {'width':img.width,'height':img.height};   //保存原来的尺寸
22                 img.width = img.height = "auto";//重写
23                 info['width'] = img.width;//获取原始尺寸
24                 info['height'] = img.height;
25                 img.width = orignInfo.width;  //还原尺寸
26                 img.height = orignInfo.height;
27             }else{
28                 info['width'] = img.width;
29                 info['height'] = img.height;
30             }
31         }
32         return info;
33     }
View Code

 

参考:http://www.cnblogs.com/rubylouvre/archive/2011/05/05/2037115.html

posted @ 2014-06-23 15:03  lmh2072005  阅读(211)  评论(0编辑  收藏  举报