function resize($imagefile, $width = false, $height = false) {
if (!$width || !$height) {
return;
}
$imginfo = getimagesize($imagefile);
$info = array(
'width' => $imginfo[0],
'height' => $imginfo[1],
'bits' => $imginfo['bits'],
'mime' => $imginfo['mime']
);
$xpos = 0;
$ypos = 0;
$scale = min($width / $info['width'], $height / $info['height']);
if ($scale == 1) {
return;
}
$mime = $info['mime'];
if ($mime == 'image/gif') {
$image = imagecreatefromgif($imagefile);
} elseif ($mime == 'image/png') {
$image = imagecreatefrompng($imagefile);
} elseif ($mime == 'image/jpeg') {
$image = imagecreatefromjpeg($imagefile);
}
$new_width = (int)($info['width'] * $scale);
$new_height = (int)($info['height'] * $scale);
$xpos = (int)(($width - $new_width) / 2);
$ypos = (int)(($height - $new_height) / 2);
$image_old = $image;
$image = imagecreatetruecolor($width, $height);
if (isset($info['mime']) && $info['mime'] == 'image/png') {
imagealphablending($image, false);
imagesavealpha($image, true);
$background = imagecolorallocatealpha($image, 255, 255, 255, 127);
imagecolortransparent($image, $background);
} else {
$background = imagecolorallocate($image, 255, 255, 255);
}
imagefilledrectangle($image, 0, 0, $width, $height, $background);
imagecopyresampled($image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $info['width'], $info['height']);
imagedestroy($image_old);
$info = pathinfo($imagefile);
$extension = strtolower($info['extension']);
if ($extension == 'jpeg' || $extension == 'jpg') {
imagejpeg($image, $imagefile, 90);
} elseif($extension == 'png') {
imagepng($image, $imagefile, 0);
} elseif($extension == 'gif') {
imagegif($image, $imagefile);
}
imagedestroy($image);
}