PHP - How do i fit my image to a defined length

Asked By Olusegun A. on 13-Jun-10 12:00 PM
Hello Friends,

Pls i need your help. I need to echo images that are uploaded by members of my site. In the space provided for the image to display is 200px by 200px. but these measurement is stretching all the images to 200px by 200px even if the uploaded image is 200px by 50px. What i want is that i want the image to be either 200px maximum in hight or 200px in width, any that come first and for the image to still maintain it's ratio.

Please help me out.

Santhosh N replied to Olusegun A. on 13-Jun-10 12:30 PM
Have the image tag placed inside the div or within td of table tag and have that to original size but have fixed width and height to the div tag or td tag...
Devil Scorpio replied to Olusegun A. on 13-Jun-10 03:22 PM
Hi There,

Please use thie PHP code to resize photo. Please change the parameter as per requirement


function imageResize($width, $height, $target) {

//takes the larger size of the width and height and applies the  
formula accordingly...this is so this script will work  
dynamically with any size image

if ($width > $height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);

//gets the new value and applies the percentage, then rounds the value
$width = round($width * $percentage);
$height = round($height * $percentage);

//returns the new sizes in html image tag format...this is so you
can plug this function inside an image tag and just get the

return "width=\"$width\" height=\"$height\"";



Before we take our new function on a test drive, we need to get the width and height of the image that we want to display. There is a magical command in PHP called getimagesize(). This command, used properly, will return the image width, height, type, and even the width and height in HTML image tag format (width="x" height="y").

$mysock = getimagesize("images/sock001.jpg");

Best Regards :)
Mohan Raj Aryal replied to Olusegun A. on 13-Jun-10 05:13 PM
hopefully your problem is resolved by above answer. If not please share your code, so that you can get better direction on what/where you have missed.