potts
potts

Reputation: 155

Cropping any image down to 4:3 ratio

I'm trying to modify an upload script, at the moment I can crop an image into a square while resizing - great!

However I would like the user to be able to upload any size image, and for the script to create 200x150, 400x300, 800x600 thumbnail/images - a 4:3 ratio.

My code so far is:

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;
 }

Does anyone know the required formula or can point me in the right direction?

Upvotes: 0

Views: 1659

Answers (1)

potts
potts

Reputation: 155

Worked out the logic using some of what was on the C# duplicate:

$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);

Upvotes: 3

Related Questions