I’m trying to create a script with GD library that will take an uploaded image of any size and create the biggest x by y thumb of it, keeping it’s proportions, and if the image is too small, it get’s the biggest x/y ratio of it and enlarges it, keeping it centered.
I’m not concerned about pixelating the image.
Take the following examples

I know it’s doable but I get stuck on calculating the x/y coordinates
Here’s where I’m at so far. I’m trying to create 3 thumbs with defined sizes
<?php
$sizes = array(
array(
'width' => 640,
'height' => 360
),
array(
'width' => 222,
'height' => 166
),
array(
'width' => 140,
'height' => 105
)
);
if (isset($_FILES['image'])) {
$file = $_FILES['image'];
foreach($sizes as $size) {
if (strpos($file['type'], 'jpeg') !== false || strpos($file['type'], 'jpg') !== false) {
$resource = imagecreatefromjpeg($file['tmp_name']);
}
else if (strpos($file['type'], 'png') !== false) {
$resource = imagecreatefrompng($file['tmp_name']);
}
else if (strpos($file['type'], 'gif') !== false) {
$resource = imagecreatefromgif($file['tmp_name']);
}
else {
echo "bad file type " . $file['type'];
exit;
}
list($width, $height) = getimagesize($file['tmp_name']);
$tmpImage = imagecreatetruecolor($size['width'], $size['height']);
/*
need to do some calculations here
*/
imagecopyresampled($tmpImage, $resource, 0, 0, 0, 0, $width, $height, $size['width'], $size['height']);
ob_start();
imagepng($tmpImage);
$image = ob_get_clean();
echo '<img src="data:image/png;base64,' . base64_encode($image) . '" />';
imagedestroy($tmpImage);
}
var_dump($file, $width, $height);
}
exit;
?>
For your consideration: