I got some code from someone here before about cropping a thumbnail so it doesn’t distort like when you resize with the wrong proportions.
I never got the code to work though. I can upload the image and it creates a thumbnail, but it doesn’t seem to crop. I want it to crop the thumbnail as a square even if the image is in rectangle format.
Maybe you can see what’s wrong in the following code
//IF FILE IS UPLOADED
if (is_uploaded_file($_FILES['thefile']['tmp_name'])){
move_uploaded_file($_FILES['thefile']['tmp_name'], $pPath.$_FILES['thefile']['name']) or die ("Couldn¥t copy");
header("Location: ../members.php");
//REMOVES AN OLD FILE IF IT'S THERE BEFORE UPLOADING A NEW ONE
if (($photo_path AND $thumb_path) !=''){
unlink("../$photo_path");
unlink("../$thumb_path");
}
// DEFINE THE FILE
$filename = $pPath.$_FILES['thefile']['name'];
$thumbname = "TN_".$_FILES['thefile']['name'];
$thumbnail = $pPath.$thumbname;
// DETERMINE FILE NAME
$myfilename = substr($filename, 3);
$mythumbname = substr($thumbnail, 3);
//INSERT QUEARY
$qry = "UPDATE members SET photo_path='$myfilename', thumb_path='$mythumbname' WHERE member_id='$member_id'";
$result = mysql_query($qry) or die("Query failed");
// GET NEW DIMENSIONS
list($width_orig, $height_orig) = getimagesize($filename);
if ($width && ($width_orig < $height_orig)) {
$per = (100*$width)/$width_orig;
$per = round($per);
$height = ($height_orig*$per)/100;
echo $height;
//($height / $height_orig) * $width_orig;
if ($width < 100){
$pre = 100 - $width;
$width = $width + $pre;
//echo $width;
}
if ($width > 100){
$pre = $width - 100;
$width = $width - $pre;
//echo $pre;
}
} else {
$height = ($width / $width_orig) * $height_orig;
}
// RESAMPLE
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// OUTPUT
imagejpeg($image_p, $pPath.$thumbname, 100);
$pasto = getimagesize($pPath.$thumbname);
link($pPath.$_FILES['thefile']['name']);
//unlink($pPath.$_FILES['thefile']['name']);
$user = 1;
$elwidth = $pasto[0];
$elheight = $pasto[1];
// CROP DIMENSIONS
$width = 100;
$height = 100;
// SET THE PATH TO THE IMAGE TO RESIZE
$input_image = $thumbname;
// GET THE SIZE OF THE ORIGINAL IMAGE INTO AN ARRAY
$size = getimagesize( $input_image );
// PREPARE CANVAS
$canvas = imagecreatetruecolor( $width, $height );
// CREATE A NEW IMAGE IN THE MEMORY FROM THE FILE
$cropped = imagecreatefromjpeg( $input_image );
// PREPARE IMAGE CROP - CENTER THE CROP OF THE IMAGE
$newwidth = $size[0] / 2;
$newheight = $size[1] / 2;
$cropLeft = ( $newwidth/2 ) - ( $width/2 );
$cropHeight = ( $newheight/2 ) - ( $height/2 );
// GENERATE THE CROPPED IMAGE
imagecopyresized( $canvas, $cropped, 0,0, $cropLeft, $cropHeight, $size[0], $size[1], $newwidth, $newheight );
// SAVE THE CROPPED IMAGE
imagejpeg( $canvas, $mythumbname );
// CLEAR THE MEMORY OF THE TEMP IMAGES
imagedestroy( $canvas );
imagedestroy( $cropped );
}