Reputation: 3514
I have an image upload script that resizes the uploaded image to 150x150 pixels. That's great if the image is square, but if someone uploads an image with let's say 640x200 pixels, it doesn't look pretty.
So I basically need it to automatically create a squared thumbnail based on the center of the image. If the image is wider it should crop off the left and right sides. If the image is higher, it should crop off the top and bottom.
I found a code modification online, here to be exact:
Upload, resize, and crop center of image with PHP
I'm not great with PHP and I've been at this for a few hours now, trying to combine my code below with the option above. If anyone could help me that would be great :)
$target_path = "avatars/";
$image = $_FILES['uploadedfile']['name'];
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$_POST["userpic"]=$_FILES['uploadedfile']['name'];
if($_FILES['uploadedfile']['tmp_name']!="") {
$imagetype=explode(".",$_POST["userpic"]);
if($imagetype[1]=="jpg" || $imagetype[1]=="JPG" || $imagetype[1]=="gif" || $imagetype[1]=="GIF")
{
$target_path = "avatars/";
$thaid=$_POST["user_id"];
$target_path = $target_path .$thaid.".".$imagetype[1];
$target_path2 =$thaid.".".$imagetype[1];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
$_POST["userpic"]=$target_path2;
$n_width=$setts['avatar_width'];
$n_height=$setts['avatar_height'];
$tsrc=$target_path;
$add=$target_path;
if($imagetype[1]=="jpg" || $imagetype[1]=="JPG")
{
$im=imagecreatefromjpeg($add);
$width=imagesx($im);
$height=imagesy($im);
$newimage=imagecreatetruecolor($n_width,$n_height);
$ar = 1.00;
if ($ar < 1) { // "tall" crop
$cropWidth = min($height * $ar, $width);
$cropHeight = $cropWidth / $ar;
}
else { // "wide" crop
$cropHeight = min($width / $ar, $height);
$cropWidth = $cropHeight * $ar;
}
imagecopyresized($newimage,$im,0,0,0,0,$n_width,$n_height,$cropWidth,$cropHeight);
imagejpeg($newimage,$tsrc,100);
}
if($imagetype[1]=="gif" || $imagetype[1]=="GIF")
{
$im=imagecreatefromgif($add);
$width=imagesx($im);
$height=imagesy($im);
$newimage=imagecreatetruecolor($n_width,$n_height);
imagecopyresized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
imagegif($newimage,$tsrc,100);
}
}
else
{
$_POST["userpic"]="noimage.jpg";
}
}
Upvotes: 2
Views: 2700
Reputation: 1944
If you have ImageMagick installed, you can do something like:
<?php
$i = new Imagick();
$i->readImage($file);
$i->cropThumbnailImage($w,$h);
This way, you don't actually have to worry about the maths.
Upvotes: 2
Reputation: 437386
The math to calculate the dimensions for the region to crop is not complicated. I 've given an answer to this question that allows you to calculate this for any aspect ratio of the crop region; since you want a square thumbnail, you should set the aspect ratio to 1.
Then, knowing the dimensions of your original image and the thumbnail it's easy to calculate the values you need to pass to imagecopyresized
.
Upvotes: 1