Sign up to create your own snipts, or login.

Public snipts » damonky's snipts » scale and crop an image to best fit a defined set of dimensions

posted on Jul 24, 2009 at 4:28 a.m. EDT in 
  • function autoCrop($file, $height, $width){
    
         //load the image file
    
         $img = false;
    
         $img = imagecreatefromjpeg($file);
    
         //quit if not loaded
    
         if(!$img){
    
              return false;
    
         }
    
         //get the image dimensions
    
         $curr = @getimagesize($file);
    
     
         $perc_w = $width / $curr[0];
    
         $perc_h = $height / $curr[1];
    
     
    
         if(($width > $curr[0]) || ($height > $curr[1])){
    
              return;
    
         }
    
     
    
         if($perc_h > $perc_w){
    
              //taller
    
              $width = $width;
    
              $height = round($curr[1] * $perc_w);
    
         } else {
    
              //wider
    
              $height = $height;
    
              $width = round($curr[0] * $perc_h);
    
         }
    
         //output
    
         $nwimg = imagecreatetruecolor($width, $height);
    
         imagecopyresampled($nwimg, $img, 0, 0, 0, 0, $width, $height, $curr[0], $curr[1]);
    
         imagejpeg($nwimg, $file);
    
     
    
         imagedestroy($nwimg);
    
         imagedestroy($img);
    
     
    
    }
    

    copy | embed

0 Comments

Sign up, or login to leave a comment.