I took a script off another site for resizing an image using GD Tools. It works properly keeping the aspect ratio the same except for when the source image is a square, and the thumbnail you want to create is not a square. I have tried to modify the script myself but it did not work. I will paste the script below and mark what I added in. The problem is that the resulting image comes out not as a square but distorted. It should take the smaller side of the rectangle and make the new square using that demension. For example:
Source Image 400x400
Thumbnail size: 200x300
Resulting Image should be 200x200 to keep the aspect ratio, however it is coming out as 300x300
Code here:
function createthumb($na me,$filename,$n ew_w,$new_h)
{
$system=explode (".",$name);
if (preg_match("/jpg|jpeg/",$system[1])){$src_img=ima gecreatefromjpe g($name);}
if (preg_match("/png/",$system[1])){$src_img=ima gecreatefrompng ($name);}
$old_x=imageSX( $src_img);
$old_y=imageSY( $src_img);
if ($old_x > $old_y)
{
$thumb_w=$new_w ;
$thumb_h=$old_y *($new_h/$old_x);
}
if ($old_x < $old_y)
{
$thumb_w=$old_x *($new_w/$old_y);
$thumb_h=$new_h ;
}
if ($old_x == $old_y)
{
// I ADDED ALL OF THIS BELOW, IT USED TO JUST DO WHAT I PUT AFTER THE ELSE.
if ($new_w < $new_h)
{
$thumb_w=$new_w ;
$thumb_h=$new_w ;
}
if ($new_h < $new_w)
{
$thumb_w=$new_h ;
$thumb_h=$new_h ;
}
else
{
$thumb_w=$new_w ;
$thumb_h=$new_h ;
}
}
$dst_img=ImageC reateTrueColor( $thumb_w,$thumb _h);
imagecopyresamp led($dst_img,$s rc_img,0,0,0,0, $thumb_w,$thumb _h,$old_x,$old_ y);
if (preg_match("/png/",$system[1]))
{
imagepng($dst_i mg,$filename);
} else {
imagejpeg($dst_ img,$filename);
}
imagedestroy($d st_img);
imagedestroy($s rc_img);
}
Source Image 400x400
Thumbnail size: 200x300
Resulting Image should be 200x200 to keep the aspect ratio, however it is coming out as 300x300
Code here:
function createthumb($na me,$filename,$n ew_w,$new_h)
{
$system=explode (".",$name);
if (preg_match("/jpg|jpeg/",$system[1])){$src_img=ima gecreatefromjpe g($name);}
if (preg_match("/png/",$system[1])){$src_img=ima gecreatefrompng ($name);}
$old_x=imageSX( $src_img);
$old_y=imageSY( $src_img);
if ($old_x > $old_y)
{
$thumb_w=$new_w ;
$thumb_h=$old_y *($new_h/$old_x);
}
if ($old_x < $old_y)
{
$thumb_w=$old_x *($new_w/$old_y);
$thumb_h=$new_h ;
}
if ($old_x == $old_y)
{
// I ADDED ALL OF THIS BELOW, IT USED TO JUST DO WHAT I PUT AFTER THE ELSE.
if ($new_w < $new_h)
{
$thumb_w=$new_w ;
$thumb_h=$new_w ;
}
if ($new_h < $new_w)
{
$thumb_w=$new_h ;
$thumb_h=$new_h ;
}
else
{
$thumb_w=$new_w ;
$thumb_h=$new_h ;
}
}
$dst_img=ImageC reateTrueColor( $thumb_w,$thumb _h);
imagecopyresamp led($dst_img,$s rc_img,0,0,0,0, $thumb_w,$thumb _h,$old_x,$old_ y);
if (preg_match("/png/",$system[1]))
{
imagepng($dst_i mg,$filename);
} else {
imagejpeg($dst_ img,$filename);
}
imagedestroy($d st_img);
imagedestroy($s rc_img);
}
Comment