Here is working snippet from my animal adoption project that cuts the middle of the image (horizontal or vertical) and makes it square, without adding white fields to the destination image:
/**
* Cuts a square image from the middle of rectangular image
* Requires: mbstring, exif, gd built-in extensions uncommented in php.ini
* Resamples rect img to square img and converts jpeg to wepp image
*
*/
function squarify($src_file,$dst_file,$square_side=600,$quality=90) {
// Deals only with jpeg
if(exif_imagetype($src_file) != IMAGETYPE_JPEG) { return 'src_not_jpeg'; }
// Convert old file into img
$src_img=imagecreatefromjpeg($src_file);
$src_side_x=imageSX($src_img);
$src_side_y=imageSY($src_img);
// Do not magnify image if its sides less than desired square side,
// issue false if image size is too small
// Remove, if you want src image be magnified
// if($src_side_x < $square_side || $src_side_y < $square_side) {
// return 'src_too_small';
// }
// Create new image
$dst_image=imagecreatetruecolor($square_side,$square_side);
// The image is square, just issue
// resampled image with adjusted square sides and image quality
if($src_side_x==$src_side_y) {
imagecopyresampled(
$dst_image,
$src_img,
0,
0,
0,
0,
$square_side,
$square_side,
$src_side_x,
$src_side_x
);
// The image is vertical, use x side as initial square side
} elseif($src_side_x<$src_side_y) {
$x1=0;
$y1=round(($src_side_y-$src_side_x)/2);
imagecopyresampled(
$dst_image,
$src_img,
0,
0,
$x1,
$y1,
$square_side,
$square_side,
$src_side_x,
$src_side_x
);
// The image is horizontal, use y side as initial square side
} else {
$x1=round(($src_side_x-$src_side_y)/2);
$y1=0;
imagecopyresampled(
$dst_image,
$src_img,
0,
0,
$x1,
$y1,
$square_side,
$square_side,
$src_side_y,
$src_side_y
);
}
// Save it to the filesystem
// imagewebp($dst_image,$dst_file,$quality);
// Or show it in the browser,
// dont forget about header('Content-type: image/webp')
imagewebp($dst_image,$dst_file,$quality);
}
And you can call this function on existing image:
if(!extension_loaded('mbstring')) { die('Err: mbstring extension not loaded.'); }
if(!extension_loaded('exif')) { die('Err: exif extension not loaded.'); }
if(!extension_loaded('gd')) { die('Err: gd extension not loaded.'); }
header('Content-type: image/webp');
squarify('images/src.jpg','images/res.webp',300,80);

