View Single Post
Old 11-16-2008, 04:01 PM   #1 (permalink)
Enfernikus
The Addict
 
Enfernikus's Avatar
 
Join Date: Jun 2008
Posts: 335
Thanks: 2
Enfernikus is on a distinguished road
Default Simple Image manipulation class [ GD ]

I find that I have to work with image a whole lot on my projects ( thumbnail creation, AJAX editing, those type of things ) so I thought other developers might have need for this to. Initially it treated the image as an object but upon modification it now works slightly differentl so as to make it easier to traverse directories with and apply effects to all the images. Take a look.


--Be aware, the effect filter is essentially a wrapper for GD's imagefilter function thus anything the imagefilter supports so does effect()

PHP Code:
$img = new imagedirname(__FILE__) . '/');
$img->set('funny-pictures-kitten-is-figuring-out-who-to-pester.jpg')
    ->
resize20 )
    ->
crop(45205201)
    ->
effect('negative')
    ->
flip('left')
    ->
execute();

$img->set('another-funny-picture.jpg')
    ->
resize20 )
    ->
crop(45205201)
    ->
effect('negative')
    ->
flip('left')
    ->
execute(); 
The above will turn




Into




Now the actual code

PHP Code:
<?php


class image
{
    private 
$supported$edit$root$image;
    
        public function 
__construct$root )
        {
            
//Check if we're working with an actual
            //Directory
            
if( is_dir($root) )
            {
                    
//Fill in the array of the things we can do
                    
$this->edit = array(
                                        
'negative'    => IMG_FILTER_NEGATE,
                                        
'greyscale'    => IMG_FILTER_GRAYSCALE,
                                        
'brightness'=> IMG_FILTER_BRIGHTNESS,
                                        
'contract'    => IMG_FILTER_CONTRAST,
                                        
'colorize'    => IMG_FILTER_COLORIZE,
                                        
'edge'        => IMG_FILTER_EDGEDETECT,
                                        
'emboss'    => IMG_FILTER_EMBOSS,
                                        
'guassion'    => IMG_FILTER_GAUSSIAN_BLUR,
                                        
'blur'        => IMG_FILTER_SELECTIVE_BLUR,
                                        
'sketch'    => IMG_FILTER_MEAN_REMOVAL,
                                        
'smooth'    => IMG_FILTER_SMOOTH
                                       
);
                                       
                  
//Fill in an array of the image formats we support
                  
$this->supported = array(
                                              
'jpeg' => 'jpeg',
                                              
'jpg'  => 'jpeg',
                                              
'png'  => 'png',
                                              
'gif'  => 'gif'
                                            
);
                
//Finally fill in the root and enforce trailing slash
                
$this->root rtrim$root'/' ) . '/';
            
            } else {
                
                throw new 
Exception("[Class Of: Image] Provided root directory does not exists");
            }
        }
        
        public function 
set$img )
        {
            
//See if our image file exists and it's supprted
            
if( file_exists$this->root $img ) )
            {
                
$type pathinfo$this->root $imgPATHINFO_EXTENSION );
                if( 
array_key_exists$type$this->supported ) )
                {
                    
                    
//Set all neccesary information
                    
$function 'imagecreatefrom' $this->supported$type ];
                    
$this->image['file']      = $img;
                    
$this->image['oResource'] = $function$this->root $img );
                    
$this->image['width']       = imagesx$this->image['oResource'] );
                    
$this->image['height']       = imagesy$this->image['oResource'] );
                    
$this->image['type']      =  $this->supported$type ];
                    
                
///Below is error reprting
                
} else {
                    
                    throw new 
Exception("[Class Of: Image] Image file is not currently supported");
                }
                
            } else {
                
                throw new 
Exception("[Class Of: Image] Image file does not exists relative to root");
            }
            
            return 
$this;
        }
        
        public function 
execute$filename '' )
        {
            
//Make a filename of one is not provided
            
if( $filename == '' )
            {
                
$filename '_edited_' $this->image['file'];
            }
            
//Create image
            
$function 'image' $this->image['type'];
            
$function$this->image['oResource'], $this->root $filename100);
            
            
//Clean cache
            
imagedestroy$this->image['oResource'] );
        }
        
        public function 
effect()
        {
            
//gather up all our arguments
            
$args func_get_args();
            
            
//Check if I support what they want done
            
if( array_key_exists$args[0], $this->edit ) )
            {
                
//Create priliminary argument array
                
$arguments = array( $this->image['oResource'], $this->edit$args[0] ]);
                unset(
$args[0]); sort$args ); //unset the unnecesaries
                
                //Now all our image filter function
                
$arguments array_merge$arguments$args );
                
call_user_func_array'imagefilter'$arguments );
                return 
$this;
            
            
///Error reporting
            
} else {
                
                throw new 
Exception("[Class Of: Gallery] Effect not supported");
            }
        }
        
        public function 
ratio$maxWidth )
        {
            
//Calculate the max height and send off to resize function
            
$maxHeight = ($maxWidth $this->image['height']) / $this->image['width'];
            
$this->resize$maxWidth$maxHeight );
        }
        
        public function 
resize$width$height '' )
        {
            if( empty(
$height) )
            {
                
//Assume width is a percentage value now
                //Check for .20 || .2 bug
                
$num = ( $num 10 ) ? '.' $num '.0' $num;
                
$width $this->image['width'] - ($this->image['width'] * $num);
                
$height $this->image['height'] - ($this->image['height'] * $num);
            }
            
//Create a temporary pallete
            
$img imagecreatetruecolor$width$height );
            
imagecopyresampled$img$this->image['oResource'], 0000$width$height$this->image['width'], $this->image['height']);
            
            
//Fill in the original with the new
            
$this->image['oResource'] = $img;
            
$this->image['width']       = $width;
            
$this->image['height']    = $height;
            
            return 
$this;
        }
        
        public function 
flip$dir )
        {
            
//Check is we support basically
            
switch( $dir )
            {
                
//The process for flipping either left and right
                //Deviates by the subtraction of one variable
                
case $dir == 'left' || $dir == 'right':
                {
                    
//Create a pallete
                    
$img imagecreatetruecolor$this->image['height'], $this->image['width'] );
                    
                    
//Begin traversing the image plane at the left uppermost corner
                    //travel down to the right down corner
                    
for( $y $this->image['height']; $y >= 0; --$y )
                    {
                        for( 
$x 0$x <= $this->image['width']; ++$x )
                        {
                            
//Extract color index
                            
$rgb imagecolorat$this->image['oResource'], $x$y );
                            
                            
//Determine side so we can check which variable to subtract from
                            
if( $dir == 'left' )
                            {
                                
imagesetpixel$img$y$this->image['width'] - $x$rgb );
                            
                            } else {
                                
                                
imagesetpixel$img$this->image['height'] - $y$x$rgb);
                            }
                        }
                    }
                    
                    
//set new height and width
                    
$this->image['width'] = imagesx$img );
                    
$this->image['height'] = imagesy$img );
                
                    break;
                }
                
                
//Down is rather simple...
                
case $dir == 'down' :
                {
                    
$img imagerotate$this->image['oResource'], 1800);
                }
            }
            
            
//set new image resource
            
$this->image['oResource'] = $img;
            
            return 
$this;
        }
        
        public function 
crop$oX$oY$nX$nY )
        {
            
//We must determine the number by which to
            //incrementing variables as well as the length
            //and height of the new image
            
if( $oX $nX )
            {
                
$xBegin $nX;
                
$xLen $oX $nX;
            } else {
                
                
$xBegin $oX;
                
$xLen $nX $oX;
            }
            
            if( 
$oY $nY )
            {
                
$yBegin $nY;
                
$yLen $oY $nY;
            } else {
                
                
$yBegin $oY;
                
$yLen $nY $oY;
            }
            
            
//Create pallete
            
$img imagecreatetruecolor$xLen$yLen );
            
            
//Begin incrementing at 0 as if traversing
            //the new image instead of the old
            
for( $y 0$y <= $yLen; ++$y )
            {
                for( 
$x 0$x <= $xLen; ++$x )
                {
                    
//Adding our pretermined value takes us the pixel
                    //location we wanted to go to
                    
$rgb imagecolorat$this->image['oResource'], $x $xBegin$y $yBegin);
                    
imagesetpixel$img$x$y $rgb );
                }
            }
            
            
//Set neccesary information
            
$this->image['oResource'] = $img;
            
$this->image['height'] = imagesy$img );
            
$this->image['width'] = imagesx$img );
            
            return 
$this;
        }
}

?>

Last edited by Enfernikus : 11-16-2008 at 07:35 PM.
Enfernikus is offline  
Reply With Quote
The Following 4 Users Say Thank You to Enfernikus For This Useful Post:
codefreek (11-16-2008), Tanax (11-16-2008), tony (11-20-2008), Y.P.Y (01-22-2009)