You can use the GD Libraries imagecopy() functions for this. There are several to choose from, but for resizing and cropping, you should use [URL=“http://www.php.net/manual/en/function.imagecopyresampled.php”]imagecopyresampled() to maintain quality.
What you’ll want to do is determine the aspect ratio of your final image, and the determine which boundary that aspect collides with first. For demonstrative purposes, let’s say you want a 16:9 picture cropped from a 4:3 image.
Original Dimensions: 800x600
Target Dimensions: 320x180
Divide the original dimensions by the targets:
Ratios: 2.5 x 3.333
The width ratio is smaller, so it hits the bounding box first, and is our starting width.
Now divide the second dimension (in this case, the height) by its ratio and multiply by the ratio from the first.
Height = (600 / 3.333) * 2.5 = 450
The height and width you now want to copy is 800x450.
To center it, get the height of the image, subtract the cropping height, and divide by 2 to get the y offset.
(600 - 450)/2 = 75
imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h );
//With our information, this would be as follows:
imagecopyresampled (resource $dst_image, resource $src_image, 0, 0, 0, 75, 320, 180, 800, 450);
Of course, you’ll be doing this with variables:
resource $dst_image, resource $src_image,
[x offset in source. Used if height hits boundary, otherwise 0], [y offset in source. Used if width hits boundary, otherwise 0],
[target image width], [target image height],
[calculated width of crop], [calculated height of crop])
I hope this helps!