I had a project that required images to be automatically cropped and resized to the exact same dimensions regardless of the original file. Automatically resizing proportionally was easy, automatically cropping to a percentile was easy, but being able to specify the dimensions and have it automatically resize and crop to fit from the center if needed, is a bit complicated!
Here’s the function. $srcimg is an image reference, not an actual file.
function Thumbnail($srcimg,$tn_w,$tn_h) {
$src_w = imagesx($srcimg);
$src_h = imagesy($srcimg);
$src_ratio = $src_w/$src_h;
if ($tn_w/$tn_h > $src_ratio) {
$new_h = $tn_w/$src_ratio;
$new_w = $tn_w;
} else {
$new_w = $tn_h*$src_ratio;
$new_h = $tn_h;
}
$x_mid = $new_w/2;
$y_mid = $new_h/2;
$newpic = imagecreatetruecolor(round($new_w), round($new_h));
imagecopyresampled($newpic, $srcimg, 0, 0, 0, 0, $new_w, $new_h, $src_w, $src_h);
$final = imagecreatetruecolor($tn_w, $tn_h);
imagecopyresampled($final, $newpic, 0, 0, ($x_mid-($tn_w/2)), ($y_mid-($tn_h/2)), $tn_w, $tn_h, $tn_w, $tn_h);
imagedestroy($newpic);
imagedestroy($srcimg);
return $final;
}
Tall images will be cropped from the center so the bottom and top are cut off. Wide images will be cropped from the center so the sides are cut off. Proportional images will remain uncropped and only resized to the dimensions you pass to this function. Here’s what it might look like in action.
The form:
<form enctype="multipart/form-data" method="post">
<input name="pic" type="file" />
<input type="submit" value="Crop and resize" />
</form>
The processing:
$img = imagecreatefromjpeg($_FILES['pic']['tmp_name']); //assuming it's a jpeg
$width = 410;
$height = 396;
$path = '/this/is/where/my/file/goes/'.$_FILES['pic']['name'];
$newimg = Thumbnail($img,$width,$height);
Imagejpeg($newimg,$path,80) //again, assuming jpeg, 80% quality
The new thumbnailed image will be placed in /this/is/where/my/file/goes with the same name as the original file. Hooray!
Initial image:

Cropped/resized:



