很多所谓的 Web 2.0 网站都会弄个用户头像什么的, 发现网上介绍的方法通常都不能达到我们想要的效果, 就是宽和高一样的~
直接使用 imagecopyresampled 可以, 不过如果高和宽本身不一样的话, 图象就不能很清晰, 我写的个函数, 模仿了 Ning.Com 使用的方法, 大家参考!
<?php
function image_resize($source_file, $output_file, $size = 100)
{
$type = exif_imagetype($source_file);
if ($type == IMAGETYPE_JPEG)
{
$source_image = imagecreatefromjpeg($source_file);
} elseif ($type == IMAGETYPE_PNG) {
$source_image = imagecreatefrompng($source_file);
} elseif ($type == IMAGETYPE_GIF) {
$source_image = imagecreatefromgif($source_file);
} else {
return FALSE;
}
list($source_width, $source_height) = getimagesize($source_file);
if ($source_height > $source_width)
{
$src_x = 0;
$src_y = ($source_height-$source_width)/2;
$src_w = $source_width;
$src_h = $source_width;
} else {
$src_x = ($source_width - $source_height)/2;
$src_y = 0;
$src_w = $source_height;
$src_h = $source_height;
}
$output_image = imagecreatetruecolor($size, $size);
$bg = imagecolorallocate($output_image, 255, 255, 255);
imagefill($output_image, 0, 0, $bg);
imagecopyresampled($output_image, $source_image, 0, 0, $src_x, $src_y, $size, $size, $src_w, $src_h);
imagejpeg($output_image, $output_file, 100);
}
image_resize('test.jpg', 'output.jpg');
?>
首发地址:
http://china.udclub.com/b/read/10008