俺的按比例裁切缩略图函数
为了减少代码量,这里直接使用了Pear::Image_Transform图片处理类,功能是按比例生成缩略图,缩小后图片效果不变形,如果超高则纵向截取,如果超长则横向截取。
/**
* 生成缩略图
*
* @param string $src 源图片路径
* @param string $dst 目标图片路径
* @param int $width 缩略图宽
* @param int $height 缩略图高
* @return bool
*/
function cropImg($src, $dst, $width, $height) {
//Pear::Image_Transform
include_once('Image/Transform.php');
$img = Image_Transform::factory('GD');
$img->load($src);
$size = $img->getImageSize();
if(empty($size[0]))
return false;
if($size[0] / $size[1] > $width / $height) {
$w = round($size[0] * $height / $size[1]);
$h = $height;
$over = 'width';
} else {
$w = $width;
$h = round($size[1] * $width / $size[0]);
$over = 'height';
}
$img->resize($w, $h);
$img->save($dst, 'jpeg', 100);
$img->free();
$img->load($dst);
$size = $img->getImageSize();
if($over == 'width') {
$x = round(($size[0] - $width) / 2);
$y = 0;
} else {
$x = 0;
$y = round(($size[1] - $height) / 2);
}
$img->crop($width, $height, $x, $y);
//die($img->display());
$img->save($dst, 'jpeg');
$img->free();
return true;
}
这里有个相似的例子:
http://www.phpx.com/happy/thread-111786-1-3.html
作者: Volcano 发表于March 13, 2006 at 3:04 pm