$maxWidth) { $newWidth = $basedOnWidth['width']; $newHeight = $basedOnWidth['height']; $y = round($maxHeight / 2) - round($newHeight / 2); } else { $newWidth = $basedOnHeight['width']; $newHeight = $basedOnHeight['height']; $x = round($maxWidth / 2) - round($newWidth / 2); } $destinationImage = imageCreateTrueColor($maxWidth, $maxHeight); if ($background === null) { $background = imagecolorallocate($destinationImage, 255, 255, 255); } imageFill($destinationImage, 1, 1, $background); imageCopyResampled($destinationImage, $image, $x, $y, 0,0, $newWidth, $newHeight, $width, $height); return $destinationImage; } /** * This will crop an image to a particular (square) size, instead of padding it * Like the above function, this resizes an image. Aspect ratio of the pixel data * is retained (i.e. you won't get any crazy streching of the image), but the actual * aspect ratio is discarded at the end. *@param imageFile string absolute path to the image file *@param resizeTo int width AND height to resize the image to. *@returns A TrueColor GD Image that is the cropped and resampled, or false if source image is not an image */ function cropImageToSize($imageFile, $resizeTo) { if (!list($width, $height, $type) = getimagesize($imageFile)) { trigger_error("Warning: image $imageFile is not an image!", E_USER_WARNING); return false; } if (!$image = createToGdImage($imageFile)) { trigger_error("Error: Could not create image from file $imageFile!", E_USER_ERROR); return false; } if ($width < $height) { $size = $width; $x = 0; $y = ($height - $width) / 2; } else { $size = $height; $y = 0; $x = ($width - $height) / 2; } $destinationImage = imageCreateTrueColor($resizeTo, $resizeTo); imageCopyResampled($destinationImage, $image, 0,0, // Destination Origin $x, $y, // Source Origin $resizeTo, $resizeTo, // Destination Size $size, $size // Source Size ); return $destinationImage; } /** * given an image file, it will return a GD image from it *@param imageFile string path to the image file to turn into a gd image *@returns resource A GD image */ function createToGdImage($imageFile) { if (function_exists("exif_imagetype")) { $type = exif_imagetype($imageFile); } else { list($dummy_w,$dummy_h,$type,$dummy_html) = getimagesize($imageFile); } switch($type) { case IMAGETYPE_GIF: return imageCreateFromGif($imageFile); case IMAGETYPE_JPEG: return imageCreateFromJpeg($imageFile); case IMAGETYPE_PNG: return imageCreateFromPng($imageFile); default: trigger_error("Error: unsupported image type: ".image_type_to_mime_type($type)." in fitImageToSize.", E_USER_WARNING); return false; } } ?>