This function support crop and resize JPEG, GIF, PNG image.
<?php /** * @author phptuts * @copyright 2012 * @link http://tutorialspots.com/ * * @return resource resized image resource * @param string $img path to image to be resized * @param int $width * @param int $height */ function image_crop_resize($img, $width, $height) { $infos = @getimagesize($img); if ($infos == false) { trigger_error("Unknown problem trying to open image.", E_USER_ERROR); } switch ($infos[2]) { case 1: $src = imagecreatefromgif($img); break; case 2: $src = imagecreatefromjpeg($img); break; case 3: $src = imagecreatefrompng($img); break; default: trigger_error("Support JPEG GIF PNG only.", E_USER_ERROR); break; } if ($src == false) { trigger_error("Unknown problem trying to open image.", E_USER_ERROR); } $ratio = (($infos[0] / $infos[1]) < ($width / $height)) ? $width / $infos[0] : $height / $infos[1]; $x = max(0, round($infos[0] / 2 - ($width / 2) / $ratio)); $y = max(0, round($infos[1] / 2 - ($height / 2) / $ratio)); $resized = imagecreatetruecolor($width, $height); $result = imagecopyresampled($resized, $src, 0, 0, $x, $y, $width, $height, round($width / $ratio, 0), round($height / $ratio)); if ($result == false) { trigger_error("Error trying to resize and crop image.", E_USER_ERROR); } else { return $resized; } } ?>
Example of usage: online demo
<?php header("Content-Type: image/png"); imagepng(image_crop_resize('http://tutorialspots.com/wp-content/uploads/2012/08/logo1.png', 200, 200)); ?>