'How to crop image like with object-fit:cover by php?

Could you help please, I crop image for thumbnail with php code below. But some pictures crops with black frames at top and bottom. How to do it properly?

$w = 265;
$h = 198;
 
if (empty($w)) {
    $w = ceil($h / ($height / $width));
}
if (empty($h)) {
    $h = ceil($w / ($width / $height));
}
 
$tmp = imageCreateTrueColor($w, $h); 
$tw = ceil($h / ($height / $width));
$th = ceil($w / ($width / $height));
if ($tw < $w) {
    imageCopyResampled($tmp, $img, ceil(($w - $tw) / 2), 0, 0, 0, $tw, $h, $width, $height);        
} else {
    imageCopyResampled($tmp, $img, 0, ceil(($h - $th) / 2), 0, 0, $w, $th, $width, $height);    
}
$img = $tmp;

Links to origninal photo and with black frames: enter image description here

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source