- 这是我用了一段时间的功能,它旨在自动保持调整后图像的约束比例
用法
imageResize('old_image.jpg', 200, 'new_image.jpg');
function imageResize($image, $thumb_width, $new_filename)
{
$max_width = $thumb_width;
//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2')) {
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}
//Get Image size info
list($width_orig, $height_orig, $image_type) = getimagesize($image);
switch ($image_type) {
case 1:
$im = imagecreatefromgif($image);
break;
case 2:
$im = imagecreatefromjpeg($image);
break;
case 3:
$im = imagecreatefrompng($image);
break;
default:
trigger_error('Unsupported filetype!', E_USER_WARNING);
break;
}
//calculate the aspect ratio
$aspect_ratio = (float) $height_orig / $width_orig;
//calulate the thumbnail width based on the height
$thumb_height = round($thumb_width * $aspect_ratio);
while ($thumb_height > $max_width) {
$thumb_width -= 10;
$thumb_height = round($thumb_width * $aspect_ratio);
}
$new_image = imagecreatetruecolor($thumb_width, $thumb_height);
//Check if this image is PNG or GIF, then set if Transparent
if (($image_type == 1) OR ($image_type == 3)) {
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
$transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
imagefilledrectangle($new_image, 0, 0, $thumb_width, $thumb_height, $transparent);
}
imagecopyresampled($new_image, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width_orig, $height_orig);
//Generate the file, and rename it to $new_filename
switch ($image_type) {
case 1:
imagegif($new_image, $new_filename);
break;
case 2:
imagejpeg($new_image, $new_filename);
break;
case 3:
imagepng($new_image, $new_filename);
break;
default:
trigger_error('Failed resize image!', E_USER_WARNING);
break;
}
return $new_filename;
}