How do I get the original size of a picture?
When setting a fixed size for IMG, how do I get the original size of the image?
#oImg { width:100px; height:100px;}
<src=id=alt="">
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.
W = document.getelementbytagname ("img")= document.getElementsByTagName (" img"). naturalheight; ' ' + h);
The printed results match the original size. However, there is a premise that the image must be completely downloaded to the client browser to determine.
If it is an unsupported version of the browser, it can be judged by the traditional method, as follows:
varOimg = document.getElementById ("oimg"), w,h; if(oimg.naturalwidth) {//HTML5 BrowsersW =Oimg.naturalwidth; H=Oimg.naturalheight; } Else { //IE 6/7/8 varNimg =NewImage (); NIMG.SRC=oimg.src; Nimg.onload=function () {W=Nimg.width; H=Nimg.height;
Console.log (W+" "+h)}}
The reason why to add onload at this point is that the picture may not be loaded, resulting in the width of the picture, height can not be obtained.
There is a case: there is a box outside the picture, and the box Display:none;
. imgbox{ width:100px; height:100px; Display:none;} class="imgbox"> <img src="images/test.jpg " id="oimg" alt=" "></div>
To create a new Image () trouble, think of another method.
var oimg = document.getElementById ( " oimg " if (oimg.naturalwidth) { // HTML5 browsers w = OI Mg.naturalwidth; H = Oimg.naturalheight; else { // IE 6/7/8 w = Oimg.width; H = Oimg.height; }console.log (w + " " + h)
But this method, under IE8, is not getting the IMG width/height. At this point, we have to do the imgbox.
0 ; Overflow:hidden;}
Now you can be compatible with IE8.
JS get the original size of the picture