将任意图像裁剪到4:3的比例


Cropping any image down to 4:3 ratio

我正在尝试修改上传脚本,现在我可以在调整大小的同时将图像裁剪成正方形-太棒了!

然而,我希望用户能够上传任何大小的图像,并让脚本创建200x150、400x300、800x600的缩略图/图像,比例为4:3。

到目前为止,我的代码是:

list($width,$height) = getimagesize($uploadedfile);
if ($thumb == 1){
if ($width > $height) {
  $y = 0;
  $x = ($width - $height) / 2;
  $smallestSide = $height;
} else {
  $x = 0;
  $y = ($height - $width) / 2;
  $smallestSide = $width;
}
// copying the part into thumbnail
$thumbSize = 200;
$tmp = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($tmp, $src, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
// write thumbnail to disk
$write_thumbimage = $folder .'/thumb-'. $image;
 switch($ext){
  case "gif":
    imagegif($tmp,$write_thumbimage);
  break;
  case "jpg":
    imagejpeg($tmp,$write_thumbimage,100);
  break;
  case "jpeg":
    imagejpeg($tmp,$write_thumbimage,100);
  break;
  case "png":
    imagepng($tmp,$write_thumbimage);
  break;
 }

有人知道所需的公式吗?或者能为我指明正确的方向吗?

使用C#副本上的一些内容来计算逻辑:

$thumb_width = 200;
$thumb_height = 150;
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect ) {
   $new_height = $thumb_height;
   $new_width = $width / ($height / $thumb_height);
} else {
   $new_width = $thumb_width;
   $new_height = $height / ($width / $thumb_width);
}
$tmp = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($tmp,
                   $src,
                   0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
                   0 - ($new_height - $thumb_height) / 2, // Center the image vertically
                   0, 0,
                   $new_width, $new_height,
                   $width, $height);