|
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($name,$filename,$new_w,$new_h)
{
$system=explode(".",$name);
if (preg_match("/jpg|jpeg/",$system[1])){$src_img=imagecreatefromjpeg($name);}
if (preg_match("/png/",$system[1])){$src_img=imagecreatefrompng($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=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thum b_w,$thumb_h,$old_x,$old_y);
if (preg_match("/png/",$system[1]))
{
imagepng($dst_img,$filename);
} else {
imagejpeg($dst_img,$filename);
}
imagedestroy($dst_img);
imagedestroy($src_img);
}
|