$source_image = 'image.jpg'; $dest_image = 'thumb.jpg'; $thumb_width = 200; $thumb_height = 200; list($width, $height) = getimagesize($source_image); $thumb = imagecreatetruecolor($thumb_width, $thumb_height); $source = imagecreatefromjpeg($source_image); if ($width > $height) { $new_height = $thumb_height; $new_width = floor($width * ($thumb_height / $height)); $offset_x = floor(($thumb_width - $new_width) / 2); $offset_y = 0; } else { $new_width = $thumb_width; $new_height = floor($height * ($thumb_width / $width)); $offset_x = 0; $offset_y = floor(($thumb_height - $new_height) / 2); } imagecopyresampled($thumb, $source, $offset_x, $offset_y, 0, 0, $new_width, $new_height, $width, $height); imagedestroy($source); imagejpeg($thumb, $dest_image, 80);
// assume original image is 640 x 480 pixels $image = imagecreatefromjpeg('image.jpg'); $cropped = imagecrop($image, ['x' => 160, 'y' => 120, 'width' => 320, 'height' => 240]); imagejpeg($cropped, 'cropped.jpg', 80);In this example, we're using PHP's GD library to crop an image. The function `imagecreatefromjpeg()` creates an image resource from the original image file. We then call `imagecrop()` to crop the image to the specified dimensions (x = 160, y = 120, width = 320, height = 240). Finally, we save the cropped image to a new file using `imagejpeg()`.