Getting the width and height of an image if its max-width property is set to some value

87 Views Asked by At

I have a img I dont know width and height of the image.So I have to fit this image inside a static width and height area,after searching for solution i got max-width property manage these kind of issue. I used max-width property for my img tag.It works great.But I confused that, how the browser calculates based on this single property ,even it does not set this width as image width.

I know how to calculate the height of the image if i know the width.

Example

original width = 100px;
original height=200px;
default width = 50px;
default height = original height/original width*default width;
default height = 200/100*50 = 100px;

Result

default width = 50px; //default static width i set
default height = 100px; //dynamic based on default width and aspect ratio

MyQuestion To find height it should have static width, but the browser(i am using mozilla), how it calculate both width and height if its max-width attribute.So does it calculates as i did?

Please help me to find this..

<img src="http://ad009cdnb.archdaily.net/wp-content/uploads/2009/11/1258661197-009-f0-reception.jpg" style="max-width:200px"/> 

1

There are 1 best solutions below

1
On

I'm still not entirely sure about the end result your looking for but I worked this up and it reports the original size as well as the modified size after adjusting only the width.

<html>
<body>

    <img id="image1">
 <hr>
 <div id="result"></div>
<script type="text/javascript">

function getImgSize(img,imgelem) {
 result = document.getElementById("result");
 width = img.width;
 height = img.height;

 document.getElementById(imgelem).width = (width*2);

 newwidth = document.getElementById(imgelem).width;
 newheight = document.getElementById(imgelem).height;

 result.innerHTML = "<br>original width: "+width+"<br>original height: "+height;
 result.innerHTML += "<br>new width: "+newwidth+"<br>new height: "+newheight;
}

img1 = new Image();
img1.src="images/example_image.gif";
document.getElementById("image1").src = img1.src;
img1.onload = function() {getImgSize(img1,"image1");};

</script>

</body>
</html>