class ImageResize { public $imageSize; function __construct($file, $newFile, $width, $height) { $this->imageSize = getimagesize($file); if($imageSize[0] > $width || $imagesSize[1] > $height) { $this->loadImage($file, $this->imageSize, $newFile, $width, $height); } else { return false; } } public function loadImage($file, $size, $newFile, $width, $height) { $originalWidth = ''; $originalHeight = ''; $originalRatio = ''; $newWidth = ''; $newHeight = ''; $fileExtension = ''; $tempImage = ''; $newImage = ''; $newFileName = ''; list($originalWidth, $originalHeight) = $size; $originalRatio = $originalWidth / $originalHeight; if($width / $height > $originalRatio) { $newWidth = $height * $originalRatio; } else { $newHeight = $width / $originalRatio; } $fileExtension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); $newImage = imagecreatetruecolor($width, $height); $newFileName = $newFile . $fileExtension; if($fileExtension == 'jpg' || $fileExtension == 'jpeg') { return $this->resizeJpeg($file, $newFileName, $newImage, $tempImage, $width, $height, $originalWidth, $originalHeight); } else if($fileExtension == 'gif') { return $this->resizeGif($file, $newFileName, $newImage, $tempImage, $width, $height, $originalWidth, $originalHeight); } else if($fileExtension == 'png') { return $this->resizePng($file, $newFileName, 9, $newImage, $width, $height, $originalWidth, $originalHeight); } else { return false; } } protected function resizeJpeg($file, $newFileName, $newImage, $width, $height, $originalWidth, $originalHeight) { $tempImage = imagecreatefromjpeg($file); imagecopyresampled($newImage, $tempImage, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight); if(!imagejpeg($newImage, $newFileName, 100)) { return false; } } protected function resizeGif($file, $newFileName, $newImage, $width, $height, $originalWidth, $originalHeight) { $tempImage = imagecreatefromgif($file); imagecopyresampled($newImage, $tempImage, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight); if(!imagegif($newImage, $newFileName)) { return false; } } protected function resizePng($file, $newFileName, $quality, $newImage, $width, $height, $originalWidth, $originalHeight) { $tempImage = imagecreatefrompng($file); imagecopyresampled($newImage, $tempImage, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight) if(!imagepng($newImage, $newFileName, $quality)) { return false; } } }