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(15010080);
?>

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$image0000$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->_newImageNULL$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->_newImageNULL$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->_newImageNULL);
            
imagedestroy($this->_newImage);
        }
        catch (
Exception $e)
        {
            echo 
"Caught exception: "$e->getMessage();
            return;
        }
    }
}