Crop image to horizontal or vertical by code based on image size

my client asked me to create gallery(WP gallery) based on this site.

the problem here is that i need to crop images based on image size before inserting the image in the Media library.

now i using this code to check the image width and height:

add_filter('wp_handle_upload_prefilter','validate_image_size');
function validate_image_size( $file ) {

$image = getimagesize($file['tmp_name']);
$image_width = $image[0];
$image_height = $image[1];

if ($image_width > $image_height) {
// crop to horizontal
}

if ($image_height > $image_width) {
// crop to vertical
}
}

1. how can i crop image to horizontal or vertical?

2. how can i show all images after crop based on the order of this site: site

always 2 vertical images in line or horizontal on line?