How do I resize an image and/or make a thumbnail of it?



Image Resize Function
This function can be used to

  1. resize an image to a more manageable size
  2. create thumbnails
It takes six parameters
  1. $file - this is the name of the original image file (required)
  2. $save - this is the name of the newly sized image (required)
  3. $t_w - this is the maximum width for the new image (required)
  4. $t_h - this is the maximum height for the new image (required)
  5. $o_path - this is the path to the original image. By making this value = " " (that's a space), the function will only look in the current folder for the image.
  6. $s_path - this is the path to store the new image. Like $o_path, it will save to the current folder, if left blank.
SPECIAL NOTES

The function is currently set to process gif, jpg and png files. The output file is jpg format

The function only duplicates or reduces an image; it does NOT enlarge the image.

By using the same name and path for both the original AND new image, the function will overwrite the original image.

This function can be incorporated into an upload script to keep images within a predetermined size AND to create thumbnails of those images

How?

Run the image through the function using the same path and name for both the original and the new image. This will replace an oversized image with a proper one.

Then run the image through a 2nd time, but use different values for the new image.


Now the actual function.

<?php 
function Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path) {
    
$s_path trim($s_path);
    
$o_path trim($o_path);
    
$save $s_path $save;
    
$file $o_path $file;
    
$ext strtolower(end(explode('.',$save)));
    list(
$width$height) = getimagesize($file) ; 
    if((
$width>$t_w) OR ($height>$t_h)) {
        
$r1 $t_w/$width;
        
$r2 $t_h/$height;
        if(
$r1<$r2) {
          
$size $t_w/$width;
        }else{
          
$size $t_h/$height;
        }
    }else{
        
$size=1;
    }
    
$modwidth $width $size
    
$modheight $height $size
    
$tn imagecreatetruecolor($modwidth$modheight) ; 
    switch (
$ext) {
        case 
'jpg':
        case 
'jpeg':
                    
$image imagecreatefromjpeg($file) ; 
        break;
        case 
'gif':
                    
$image imagecreatefromgif($file) ; 
        break;
        case 
'png':
                    
$image imagecreatefrompng($file) ; 
        break;
    }
    
imagecopyresampled($tn$image0000$modwidth$modheight$width$height) ; 
    
imagejpeg($tn$save100) ; 
    return;
}

#####################
#
#    Example usage
#
#####################

$save 'myfile.jpg'
$file 'original.jpg'
 
$t_w 120;
$t_h 120;
$o_path " ";
$s_path " ";

Resize_Image($save,$file,$t_w,$t_h,$s_path,$o_path);
?>