JS Quick Method of obtaining picture width and height

Source: Internet
Author: User
Tags diff

Quickly get the width of the picture is in order to pre-make layout-style layouts to prepare, by quickly obtaining a picture of the width of the method than the OnLoad method to save a lot of time, even more than a minute is possible, and this method is applicable to mainstream browsers including IE low-version browser.

We step into the process.

A simple way to get pictures
1234567891011 //picture address is appended with timestamps to avoid caching var img_url = ' http://www.qttc.net/static/ Upload/2013/13643608813441.jpg? ' +date.parse ( new date ());  //creating objects var img = new image ();  //Change the image of Src img.src = Img_url;  //print alert ( +img.width+ +img.height);

Perform:

The width of the height is 0 of the result is normal, because the image of the relevant data is not loaded before its width and height default is 0

So you can optimize!

Second, the onload after the printing
1234567891011121314 // 图片地址 后面加时间戳是为了避免缓存var img_url = ‘http://www.qttc.net/static/upload/2013/13643608813441.jpg?‘+Date.parse(new Date());// 创建对象var img = new Image(); // 改变图片的srcimg.src = img_url;// 加载完成执行img.onload = function(){    // 打印    alert(‘width:‘+img.width+‘,height:‘+img.height);};

Perform:

The width of the image can be obtained by the onload. But the onload larger figure is usually slow, not practical, but as long as the picture is cached by the browser, then the picture loading almost without waiting to trigger onload, we want a placeholder. So some people get through the cache and can write like this.

Iii. mixing with onload through complete

To test the cache effect, note that the URL of the following test picture is not timestamp

1234567891011121314151617181920 // 图片地址var img_url = ‘http://www.qttc.net/static/upload/2013/13643608813441.jpg‘;// 创建对象var img = new Image();// 改变图片的srcimg.src = img_url;// 判断是否有缓存if(img.complete){    // 打印    alert(‘from:complete : width:‘+img.width+‘,height:‘+img.height);}else{    // 加载完成执行    img.onload = function(){        // 打印        alert(‘from:onload : width:‘+img.width+‘,height:‘+img.height);    };}

The first execution, always the OnLoad trigger

You refresh again, almost all cache triggers.

Read the picture from the cache the width of the height needless to say, very convenient and fast, today we have to solve is not cached and fast compared to onload faster way to get the width of the picture. We often know that some images, although not completely down, have placeholders and then load 1.1 points. Since there is a placeholder that should be returned after requesting a response from the picture resource server. When the server responds and returns a wide data without triggering an event, such as the OnLoad event. So the fourth method was spawned.

Four, through the timing cycle detection to obtain

Take a look at the following example, in order to avoid reading data from the cache, each request has a timestamp:

1234567891011121314151617181920212223 // 图片地址var img_url = ‘http://www.qttc.net/static/upload/2013/13643608813441.jpg?‘+Date.parse(new Date()); // 创建对象var img = new Image();// 改变图片的srcimg.src = img_url;// 定时执行获取宽高var check = function(){    document.body.innerHTML += ‘<div>from:<span style="color:red;">check</span> : width:‘+img.width+‘,height:‘+img.height+‘</div>‘;};var set = setInterval(check,40);// 加载完成获取宽高img.onload = function(){    document.body.innerHTML += ‘<div>from:<span style="color:blue">onload</span> : width:‘+img.width+‘,height:‘+img.height+‘</div>‘;    // 取消定时获取宽高    clearInterval(set);};

FireFox

IE7 8 9 10

Chrome

Through the above tests, we found that the time to detect the image width is much faster than onload, the more lines printed to indicate that the onload time is longer, 40 milliseconds to execute once, the basic 100 milliseconds to obtain the width of the picture, Chrome even in the first cycle when the data has been obtained. From the above data to analyze, in fact, we can judge in the timing function as long as the width of the picture is greater than 0 indicates that the image has been obtained the correct width of the height. Let's take the time to see how much time it takes to get a wide height or the onload by timing.

Code:

123456789101112131415161718192021222324252627282930 // 记录当前时间戳var start_time = new Date().getTime();// 图片地址var img_url = ‘http://b.zol-img.com.cn/desk/bizhi/image/2/2560x1600/1365477614755.jpg?‘+start_time; // 创建对象var img = new Image();// 改变图片的srcimg.src = img_url;// 定时执行获取宽高var check = function(){    // 只要任何一方大于0    // 表示已经服务器已经返回宽高    if(img.width>0 || img.height>0){        var diff = new Date().getTime() - start_time;        document.body.innerHTML += ‘<div>from:<span style="color:red;">check</span> : width:‘+img.width+‘,height:‘+img.height+‘, time:‘+diff+‘ms</div>‘;        clearInterval(set);    }};var set = setInterval(check,40);// 加载完成获取宽高img.onload = function(){    var diff = new Date().getTime() - start_time;    document.body.innerHTML += ‘<div>from:<span style="color:blue">onload</span> : width:‘+img.width+‘,height:‘+img.height+‘, time:‘+diff+‘ms</div>‘;};

FireFox:

Ie

Chrome

This is a 2560 * 1600 size picture, the browser execution results can be seen by the rapid acquisition of image size is almost within 200 milliseconds, and onload at least five seconds or more, the difference between the big picture is very useful to quickly get the image width.

Five. HTML5 new features

HTML5 provides a new property naturalwidth/naturalheight can directly get the original width height of the picture. These two properties have been implemented in Firefox/chrome/safari/opera and IE9. The method of obtaining the image size under the Reformation.

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] }

Note that the IE6/7/8 processing, created a new IMG, only set its SRC, it is necessary to let the picture fully loaded before you can get its width height. So here is the asynchronous, can pass a callback, the callback in the original width and height as a parameter passed in.

JS Quick Method of obtaining picture width and height

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.