During my web development work, I need to make pretty looking square thumbnails, which will be smartly cut out from the bigger picture. Experimenting a lot with various methods, I found the best suitable one for me.
First of all, I want to show the function I use for these purposes
function cropthumb ($image,$dest_image,$width,$height, $indexX, $indexY) { $img = imagecreatetruecolor($width,$height); $arr = split("\.",$image); $ext = $arr[count($arr)-1]; if(preg_match('/jpeg/i', $ext)){ $org_img = imagecreatefromjpeg($image); }elseif (preg_match('/jpg/i', $ext)){ $org_img = imagecreatefromjpeg($image); } elseif(preg_match('/png/i', $ext)){ $org_img = imagecreatefrompng($image); } elseif(preg_match('/gif/i', $ext)) { $org_img = imagecreatefromgif($image); }else { $org_img = imagecreatefromjpeg($image); } imagecopy($img,$org_img, 0, 0, $indexX, $indexY, $width, $height); if(preg_match('/jpeg/i', $ext)){ imagejpeg($img,$dest_image,90); }elseif (preg_match('/jpg/i', $ext)){ imagejpeg($img,$dest_image,90); } elseif(preg_match('/png/i', $ext)){ imagepng($img,$dest_image,90); } elseif(preg_match('/gif/i', $ext)) { imagegif($img,$dest_image,90); } imagedestroy($img); return true; }
This function is intended to cut thumbnail $dest_image of a proper form from $image, which left top corner will start on $indexX, $indexY coordinates and will have sizes $width,$height.
So, let’s look at an example.
Imagine, we have a picture size 600x1000px. We need to get thumbnail size 150x150px. So, the picture smaller size will be reduced to 150px and the largest will be cut, so that to get the picture from the middle.
First of all, we’ll create a smaller version of our big file. We are using function createthumb, as it was described in this article. In this case we are making picture smaller by the smallest size.
createthumb ($targetFile_big, $targetFile_temp, 150, 150);
As a result our $targetFile_temp image will have the following size 150x250px.
// we get exact sizes of the resulting image list($file_x, $file_y, $type, $attr) = getimagesize($targetFile_temp); if($file_x > $file_y) { // if width is bigger then height, then we get X position, by counting (250-150)/2 = 50px. $position=($file_x-150)/2; // cropping image with X position 50px and Y position 0px. In this case, 50px-sized borders will be cut from left and right. $output = cropthumb ($targetFile_temp, $thumbFile, 150, 150, $position, 0); }elseif ($file_x < $file_y){ // if width is smaller then height, then we get Y position, by counting (250-150)/2 = 50px. $position=($file_y-150)/2; // cropping image with Y position 50px and X position 0px. In this case, 50px-sized borders will be cut from top and bottom. $output = cropthumb ($targetFile_temp, $thumbFile, 150, 150, 0, $position); }else{ // if width and height are equal, then it just copy the file to target destination. $output = cropthumb ($targetFile_temp, $thumbFile, 150, 150, 0, 0); }