Jump to content

resizing images while keeping aspect ratio


Lt_Wolf

Recommended Posts

I am making a website that displays a lot of images, but some of the images are too wide to fit inside the layout properly without getting "squished".  I was wondering if there is some way to define a maximum width for a picture, while maintaining its aspect ratio. 

If the size of the image is not excessively large, setting it in HTML is fine. If the images are large... and say you want a thumbnail view and a full image view, you probably don't want to do that or you can significantly slow down the loading of your pages.

 

I've got the code that does this laying around somewhere, I'll give you some pseudo code for the logic.

 

//get the current dimensions of the image by using some gd functions
//this will resize by width

$max_width = 200;

$scalefactor = 1;
if( $current_width > $max_width ) //only resize if it's bigger than our max
{
   $scalefactor = $current_width / $max_width; //we want to resize the height & width proportionally
}

$new_width = $current_width / $scalefactor;
$new_height = $current_height / $scalefactor;

//then you use the gd functions to actually create the image and write it to file or whatever

 

I hope this helps get you going in the right direction.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.