Forum Moderators: coopster

Message Too Old, No Replies

Image Resizing Script - height and width issue

         

matthewamzn

12:20 am on Feb 1, 2007 (gmt 0)

10+ Year Member



This is a code snippet from a page on my site. It's meant to resize avatars if they are to large. I want the avatars to be shruncken to the smallest allowed dimension (120*180 pixels).

The problem comes if the image's height is larger than it's width. In this case the image is resized, but with a width that is larger than allowed (example 160x180). I can't see where the problem is?

---------------------------------

// If avatar is to large, resize
$width = $sizes[0];
$height = $sizes[1];
if($width > $admin_info[avatar_width] OR $height > $admin_info[avatar_height]) {

// Set a maximum height and width
$widthr = $admin_info[avatar_width];
$heightr = $admin_info[avatar_height];

// Get new dimensions
list($width_orig, $height_orig) = $sizes;

if ($widthr && ($width_orig < $height_orig)) {
$widthr = ($heightr / $height_orig) * $width_orig;
} else {
$heightr = ($widthr / $width_orig) * $height_orig;
}

// Resample
$image_p = imagecreatetruecolor($widthr, $heightr);
if($ext == "jpg" OR $ext == "jpeg")
{$image = imagecreatefromjpeg($file_tempname);}
elseif($ext == "gif") {$image = imagecreatefromgif($file_tempname);}
elseif($ext == "png") {$image = imagecreatefrompng($file_tempname);}

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $widthr, $heightr, $width_orig, $height_orig);

// Output
imagejpeg($image_p, $file_tempname, 100);
ImageDestroy($image_p);
ImageDestroy($file_tempname);
}

phranque

1:06 am on Feb 1, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



try something like this:

// maximum height and width
$width_max = $admin_info[avatar_width];
$height_max = $admin_info[avatar_height];

// original dimensions
list($width_orig, $height_orig) = $sizes;

// initialize reduced dimensions
$heightr = $height_orig;
$widthr = $width_orig;

// if height exceeds max, scale down dimensions
if ($height_max < $heightr) {
$heightr = $height_max;
$widthr = ($height_max / $height_orig) * $width_orig;
}

// if width still exceeds max, further scale down dimensions
if ($width_max < $widthr) {
$heightr = ($width_max / $widthr) * $heightr;
$widthr = $width_max;
}

matthewamzn

7:41 pm on Feb 1, 2007 (gmt 0)

10+ Year Member



Thanks that worked great.