JavaScript get picture Width High Example Summary

Source: Internet
Author: User
Tags diff setinterval

A simple way to get pictures

The code is as follows Copy Code

The time stamp behind the picture address is to avoid caching
var img_url = '/static/upload/2013/13643608813441.jpg? ' +date.parse (New Date ());
Creating objects
var img = new Image ();
Change the src of the picture
IMG.SRC = Img_url;
Print
Alert (' Width: ' +img.width+ ', Height: ' +img.height);

Perform:

The width is 0, the result is normal, because the picture has no data to be loaded before it's wide and high default is 0
So it can be optimized!

Second, the onload after printing

The code is as follows Copy Code
The time stamp behind the picture address is to avoid caching
var img_url = '/static/upload/2013/13643608813441.jpg? ' +date.parse (New Date ());
Creating objects
var img = new Image ();
Change the src of the picture
IMG.SRC = Img_url;
Load Complete execution
Img.onload = function () {
Print
Alert (' Width: ' +img.width+ ', Height: ' +img.height);
};

Perform:

Through the onload can get the picture of the wide height. 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 do not have to wait to trigger the onload, we want to be placeholders. So some people can also write this by caching.

Third, through the complete and the onload mixed use

To test the caching effect, note that the following test picture's URL does not add a timestamp

The code is as follows Copy Code
//photo address     
var img_url = '/static/upload/2013/13643608813441.jpg ';   
//Create Object   & nbsp
var img = new Image ();   
//Change src   
Img.src = img_url;   
//Determine if there is a cache    
if (img.complete) {   
   //Print   & nbsp
    alert (' from:complete:width: ' +img.width+ ', Height: ' +img.height);   
} else{   
   //load Complete execution    
    img.onload = function () {   
       //printing    
         alert (' from:onload:width: ' +img.width+ ', Height: ' +img.height ');    
   };   
}

The first execution, always the OnLoad trigger

You refresh again, almost all of the cache triggers

Read the width of the picture from the cache needless to say, very convenient and fast, today we have to solve is not cached and fast compared to the onload faster way to get the picture of the width of the height. We often know that some pictures are not completely down, but they already have placeholders, and then 1.1 points of loading. Since there are placeholders that should be returned after the request for a picture resource server response. When the server responds and returns a wide range of data without triggering an event, such as the OnLoad event. And then a fourth method was created.

Four, through the regular 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:

The code is as follows Copy Code
Picture Address
var img_url = '/static/upload/2013/13643608813441.jpg? ' +date.parse (New Date ());
Creating objects
var img = new Image ();
Change the src of the picture
IMG.SRC = Img_url;
Timed execution gets a wide-high
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);
Load Complete Get width high
Img.onload = function () {
Document.body.innerHTML = ' <div>from:<span style= ' Color:blue ' >onload</span>: Width: ' +img.width+ ', Height: ' +img.height+ ' </div> ';
Cancel timed gain width high
Clearinterval (set);
};
FireFox
IE7 8 9 10
Chrome

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

The code is as follows Copy Code

var start_time = new Date (). GetTime ();
Picture Address
var img_url =/desk/bizhi/image/2/2560x1600/1365477614755.jpg? ' +start_time;
Creating objects
var img = new Image ();
Change the src of the picture
IMG.SRC = Img_url;
Timed execution gets a wide-high
var check = function () {
As long as either party is greater than 0
Indicates that the server has already returned a wide height
if (img.width&gt;0 | | img.height&gt;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);
Load Complete Get width high
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 of the picture, the results of each browser can be seen by the rapid acquisition of image size almost all within 200 milliseconds, and the onload at least five seconds above, the difference is that the rapid acquisition of picture width is very practical

Finally, to add a common online js to get a picture of the high width of the code

JS get the actual width of the picture, and according to the size of the image adaptive

The code is as follows Copy Code

function adapt () {
var tablewidth = $ ("#imgTable"). width (); Table width
var img = new Image ();
Img.src =$ (' #imgs '). attr ("src");
var imgwidth = img.width; Picture actual width
if (imgwidth<tablewidth) {
$ (' #imgs '). attr ("style", "Width:auto");
}else{
$ (' #imgs '). attr ("style", "width:100%");
}
}

JS dynamically get the size of the picture

The code is as follows Copy Code
var _w = parseint ($ (window). width ());//Get browser widths
$ (". New_mess_c img"). each (function (i) {
var img = $ (this);
The true width of Var realwidth;//
The true height of Var realheight;//
Here's how to do this, $ ("$ ("/*
If you want to get the true width and height of the picture there are three points to note
1, need to create an image object: such as Here $ ("2, specify the SRC path of the picture
3, must be in the picture after the completion of loading, such as. load () function execution
*/
Realwidth = This.width;
Realheight = This.height;
If the true width is greater than the width of the browser, show 100%
if (realwidth>=_w) {
$ (IMG). CSS ("width", "100%"). CSS ("height", "Auto");
}
else{//if the width of the browser is less than the original size display
$ (IMG). CSS ("width", realwidth+ ' px '). CSS ("height", realheight+ ' px ');
}
});
});

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.