PHP Image Resizer
Download
Used Like
<?php
require_once("ImageResizer.php");
$filename = "imagefile";
//Instantiates the resizer
$resizer = new ImageResizer($filename);
//Outputs image to the screen
$resizer->jpeg(150, 100, 80);
?>
ImageResizer Class
<?php
class ImageResizer
{
private $_imageData;
private $_newImage;
function __construct($file)
{
$data = file_get_contents($file);
try
{
$this->_imageData = $this->getImageData($data);
}
catch (Exception $e)
{
echo "Caught exception: ", $e->getMessage();
}
}
private function getImageData($data)
{
if($imageData = @imagecreatefromstring($data))
{
return $imageData;
}
else
{
imagedestroy($imageData);
throw new Exception ("Not a valid image file.");
}
}
private function convertImage($image, $width, $height)
{
$orig_width = imagesx($image);
$orig_height = imagesy($image);
$this->_newImage = imagecreatetruecolor($width, $height);
if(imagecopyresampled($this->_newImage, $image, 0, 0, 0, 0, $width, $height, $orig_width, $orig_height))
{
return $this->_newImage;
}
else
{
throw new Exception ("Not a valid image file.");
}
}
public function jpeg($width, $height, $quality)
{
try
{
$image = $this->convertImage($this->_imageData, $width, $height);
header('Content-Type: image/jpeg');
imagejpeg($this->_newImage, NULL, $quality);
imagedestroy($this->_newImage);
}
catch (Exception $e)
{
echo "Caught exception: ", $e->getMessage();
return;
}
}
public function png($width, $height, $quality)
{
try
{
$image = $this->convertImage($this->_imageData, $width, $height);
header('Content-Type: image/png');
imagepng($this->_newImage, NULL, $quality);
imagedestroy($this->_newImage);
}
catch (Exception $e)
{
echo "Caught exception: ", $e->getMessage();
return;
}
}
public function gif($width, $height)
{
try
{
$image = $this->convertImage($this->_imageData, $width, $height);
header('Content-Type: image/gif');
imagegif($this->_newImage, NULL);
imagedestroy($this->_newImage);
}
catch (Exception $e)
{
echo "Caught exception: ", $e->getMessage();
return;
}
}
}