PHP crop image to fix width and height without losing dimension ratio

This is done by only using a part of the image as the thumbnail which has a 1:1 aspect ratio (mostly the center of the image). If you look closely you can see it in the flickr thumbnail.

Because you have “crop” in your question, I’m not sure if you didn’t already know this, but what do you want to know then?

To use cropping, here is an example:

//Your Image
$imgSrc = "https://stackoverflow.com/questions/3255773/image.jpg";

//getting the image dimensions
list($width, $height) = getimagesize($imgSrc);

//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc);

// calculating the part of the image to use for thumbnail
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 = 100;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);

Leave a Comment