I was looking around and couldn't find a function that resizes images to any ratio without leaving a blank area, so i wrote this one. It's able to resize images to any size ratio, when the ratio is no match with the original it will crop proportional area on the original and resize it.
<?php
function _ckdir($fn) {
if (strpos($fn,"/") !== false) {
$p=substr($fn,0,strrpos($fn,"/"));
if (!is_dir($p)) {
_o("Mkdir: ".$p);
mkdir($p,777,true);
}
}
}
function img_resizer($src,$quality,$w,$h,$saveas) {
$r=1;
$e=strtolower(substr($src,strrpos($src,".")+1,3));
if (($e == "jpg") || ($e == "peg")) {
$OldImage=ImageCreateFromJpeg($src) or $r=0;
} elseif ($e == "gif") {
$OldImage=ImageCreateFromGif($src) or $r=0;
} elseif ($e == "bmp") {
$OldImage=ImageCreateFromwbmp($src) or $r=0;
} elseif ($e == "png") {
$OldImage=ImageCreateFromPng($src) or $r=0;
} else {
_o("Not a Valid Image! (".$e.") -- ".$src);$r=0;
}
if ($r) {
list($width,$height)=getimagesize($src);
$_ratio=array($width/$height,$w/$h);
if ($_ratio[0] != $_ratio[1]) { $_scale=min((float)($width/$w),(float)($height/$h));
$cropX=(float)($width-($_scale*$w));
$cropY=(float)($height-($_scale*$h));
$cropW=(float)($width-$cropX);
$cropH=(float)($height-$cropY);
$crop=ImageCreateTrueColor($cropW,$cropH);
ImageCopy(
$crop,
$OldImage,
0,
0,
(int)($cropX/2),
(int)($cropY/2),
$cropW,
$cropH
);
}
$NewThumb=ImageCreateTrueColor($w,$h);
if (isset($crop)) { ImageCopyResampled(
$NewThumb,
$crop,
0,
0,
0,
0,
$w,
$h,
$cropW,
$cropH
);
ImageDestroy($crop);
} else { ImageCopyResampled(
$NewThumb,
$OldImage,
0,
0,
0,
0,
$w,
$h,
$width,
$height
);
}
_ckdir($saveas);
ImageJpeg($NewThumb,$saveas,$quality);
ImageDestroy($NewThumb);
ImageDestroy($OldImage);
}
return $r;
}
?>