Wednesday, July 15, 2009

Image Compression

Nowadays it is common to work with images in programming language. Here I m putting some image compression function which can use in PHP. This is comes to common when developer working with image uploading and stuffz. Bcoz due to the storage matter we have to reduce images capacities to manage it.

It’s better to execute image compression PHP script in uploading page than ask user to do it.

Before using this script you have to enable GD library in your web server. And it’s better to enable EXIF library too when you are going to validate the image header files.

1 ) Script automatically compress the image base on the given dimension.
2 ) Automatically calculate the landscape image or portrait image.


function imageCompression($imgfile="",$thumbsize=0,$savePath=NULL) {

if($savePath==NULL) {
          header('Content-type: image/jpeg');
     }
 
     list($width,$height)=getimagesize($imgfile);
     $imgratio=$width/$height; 

     if($imgratio>1) {
          $newwidth = $thumbsize;
          $newheight = $thumbsize/$imgratio;
     } else {
          $newheight = $thumbsize;       
          $newwidth = $thumbsize*$imgratio;
     }
   
 // Making a new true color image
    $thumb=imagecreatetruecolor($newwidth,$newheight); 

 // Now it will create a new image from the source
     $source=imagecreatefromjpeg($imgfile); 

 // Copy and resize the image
 imagecopyresampled($thumb,$source,0,0,0,0,$newwidth,$newheight,$width,$height);  
     imagejpeg($thumb,$savePath,100);

    imagedestroy($thumb);
   
}



This imageCompression() you have to pass 3 parameter to execute.
// 1 - Source of your image file.
// 2 - Output image dimension.
// 3 - Destination path of the image.



imageCompression($uploadfile,250,$uploadfile);


No comments: