Link to home
Start Free TrialLog in
Avatar of steverguy
steverguy

asked on

Javascript Image Uploader

I have the following Javascript code that is intended to resize images that are larger than the specified width.  I'm not fluent in Javascript, so although I can kind of figure out what this code is doing, I'm not 100% sure.  The whichId and maxW are passed from the:
<body onload="fixImgs('photos', 50) /*('element ID', maximum width)*/">

in my HTML code I have an image: <img src="../../UserImages/<%=imgPath%>/<%=Picture%>" id="photos" border=0 align="left">

My hope was that the Javascript would check to see if the image was over 50pixels wide (or whatever number) and if it was, it would resize it.

I can't get it to work.

function fixImgs(whichId, maxW) {
var pix=document.getElementById(whichId);
  for (i=0; i<pix.length; i++) {
    w=pix[i].width;
    h=pix[i].height;
    if (w > maxW) {
      f=1-((w - maxW) / w);
      pix[i].width=w * f;
      pix[i].height=h * f;
    }
  }
}
Any Suggestions?

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Also if you don't want to bother with javascript you could probably just set the width in the img tag and in most browsers it will resize properly. This would make all images width be 50 even if they were smaller previously.

<img src="picturesourcehere" width="50">
Also if you go with the javascript function to handle this issue,

if you don't want smaller images to get bigger then add an if statement around it that checks that first.


function fixImgs(whichId,maxW)
{
  var pix = document.getElementById(whichId)
  if (pix.width >50)
  {
     var ratio = maxW / pix.width;
     pix.width = 50;
     pix.height = pix.height * ratio;
  }
}
and you can replace the 50's in there with maxW

Sorry about the multiple posts. I haven't had my coffee yet.
Avatar of steverguy
steverguy

ASKER

Thank you for your help!  I appreciated the insight, jrm.