Resize image using PHP and maintaining aspect ratio.

@mit $ingh. April 01, 2016 Comments

I had written a peice of code like this for another project I've done. I've copied it below, might need a bit of tinkering! (It does required the GD library)

These are the parameters it needs

$image_name	:	#Name of the image which is uploaded
$new_width	:	#Width of the resized photo (maximum)
$new_height	:	#Height of the resized photo (maximum)
$uploadDir	:	#Directory of the original image
$moveToDir	:	#Directory to save the resized image

It will scale down or up an image to the maximum width or height

function createThumbnail($image_name,$new_width,$new_height,$uploadDir,$moveToDir){
    $path = $uploadDir . '/' . $image_name;

    $mime = getimagesize($path);

    if($mime['mime']=='image/png'){ $src_img = imagecreatefrompng($path); }
    if($mime['mime']=='image/jpg'){ $src_img = imagecreatefromjpeg($path); }
    if($mime['mime']=='image/jpeg'){ $src_img = imagecreatefromjpeg($path); }
    if($mime['mime']=='image/pjpeg'){ $src_img = imagecreatefromjpeg($path); }

    $old_x          =   imageSX($src_img);
    $old_y          =   imageSY($src_img);

    if($old_x > $old_y){
        $thumb_w    =   $new_width;
        $thumb_h    =   $old_y*($new_height/$old_x);
    }elseif($old_x < $old_y){
        $thumb_w    =   $old_x*($new_width/$old_y);
        $thumb_h    =   $new_height;
    }elseif($old_x == $old_y){
        $thumb_w    =   $new_width;
        $thumb_h    =   $new_height;
    }

    $dst_img  =  ImageCreateTrueColor($thumb_w,$thumb_h);

    imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 


    // New save location
    $new_thumb_loc = $moveToDir . $image_name;

    if($mime['mime']=='image/png'){ $result = imagepng($dst_img,$new_thumb_loc,8); }
    if($mime['mime']=='image/jpg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
    if($mime['mime']=='image/jpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }
    if($mime['mime']=='image/pjpeg'){ $result = imagejpeg($dst_img,$new_thumb_loc,80); }

    imagedestroy($dst_img); 
    imagedestroy($src_img);

    return $result;
}

 

  • PHP
  • image
  • resize