Whilst writing several applications i have wanted needed to automate the process of resizing and cropping an image to fit, for example for sites which have catalogues.
After getting just a little bit more than bored of photoshopping 300+ images i decided to write my own function to automate the re-size. The function below will take a file reference, load the file, find the best fit for the desired output size and crop / re-size accordingly.
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);
}
Guess
June 26th, 2008 at 3:57 pm
Why not use a Photoshop batch function?
You can even avoid pixel shifts if done right