将任何图像裁剪为4:3比例

时间:2015-02-12 12:15:23

标签: php gd

我正在尝试修改上传脚本,此时我可以在调整大小时将图片裁剪为正方形 - 很棒!

但是我希望用户能够上传任意大小的图像,并且脚本可以创建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;
 }

有人知道所需的公式还是能指出我正确的方向?

1 个答案:

答案 0 :(得分:3)

使用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);