Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Code in JS that will take Width & Height and scale to proportion

Status
Not open for further replies.

RodS2

IS-IT--Management
Sep 11, 2007
33
US
I am creating a website in which we will be importing tons of image files and we want to create functionality to scale down the images so they fit within a certain area, but remain in proportion. The display area is 200 x 200, and we have included light-gray boxes so there is a clear divider, since each image within the box can potentially be different in size to the one next to it.

We need the images to resize to fit in the 200 x 200 area, but remain in proportion. The images range in various sizes, so we cannot just manually plug them in. So for example, one image could be 220 x 300 (just an example) and the image should scale down to fit in the 200 x 200 in proportion.

Thanks for your help.
 
It's quite easy to display images like you want, but the page will still download the entire original image before resizing and displaying it. If you want to actually resize the image first, you'll need to use something like PHP to do that.

Otherwise, load the images as Image() objects and resize them there. Something like this should work:

Code:
<img id="sizedimage">
<script type="text/javascript">

var maxwidth = 200;
var maxheight = 200;
var imgfolder = 'images/';

var imgname = new Array(), ii = 0;
imgname[ii++] = 'image1.jpg';
imgname[ii++] = 'secondimage';
//etc

var imgs = new Array();

for (ii = 0; ii < imgname.length; ii++)
  {
  var oneimage = new Image();
  oneimage.src = imgfolder + imgname[ii];
  if (oneimage.height > oneimage.width)
    {
    oneimage.height = maxheight;
    }
  else
    {
    oneimage.width = maxwidth;
    }
  imgs[ii] = oneimage;
  }
document.getElementById('sizedimage').src = imgs[0].src;
</script>

This is to load all images onto the page at once. If you only want to display one image on a page, you can use the same principle but only work with one Image() object rather than creating an array of them.

Lee
 
Trollacious, this does not seem to be working. is there any other way?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top