Tuesday, October 9, 2012

How to get Height and Widht of an Image using JavaScript

I got one problem during my project development. When I click on thumbnails to show image in pop up window, it does not appear in first click but on the second click it works. It only does work when the image exist is browser cache. And we had to show image on sigle click as per the client requirement. I got the solution and want to share with all of you. :)
Second requirement is that if image aspect ration is greater than 500 then reduce to 500.

<script type="text/javascript" language="javascript1.2">
var imgHeight;
var imgWidth;

function findHHandWW() {
imgHeight = this.width;imgWidth = this.width;return true;
}
function showImage(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHHandWW;
myImage.src = imgPath;
}
</script>


This is main code to get height and width of an image using javascript.

Now, I am giving complete code to how you will show pop up window after click on thumbnail image.

1. ThumbsNail.jsp

<html><head><title>Binod Java Solution</title></head>
<script type="text/javascript" language="javascript1.2">
var imgHeight;
var imgWidth;
var winHeight;
var winWidth;

function findHHandWW() {
imgHeight = this.width; imgWidth = this.width; return true;
}

function openWin(imgPath) {
var myImage = new Image();
myImage.name = imgPath;
myImage.onload = findHHandWW;
myImage.src = imgPath;
if(imgHeight>=500){imgHeight=500;}if(imgWidth>=500){imgWidth=500;}
winHeight = imgHeight + 60;winWidth = imgWidth + 30;

var url1="Image.jsp?myPath="+imgPath+"&hh="+imgHeight+"&ww="+imgWidth;
window.open(url1,"","width="+winWidth+",height="+winHeight+",status=yes,toolbar=no,
scrollbars=no,left=100,top=100");
}

</script>

<body>
<img src="c:\\Binod.JPG" height="85" width="85" onclick="openWin('c:\\Binod.JPG')" />
</body>
</html>

2. Image.jsp

<html><head><title>Binod Java Solution</title></head>

<script type="text/javascript">
function closeWin(){ window.close(); }
</script><body>

<%
String imagePath = request.getParameter("myPath");
String hh = request.getParameter("hh");
String ww = request.getParameter("ww");
%>

<img src="<%=imagePath%>" height="<%=hh%>" width="<%=ww%>" />
<center><input type="button" value="Close" onclick="closeWin()" /> </center>
</body>
</html>

0 comments:

Post a Comment