增加了裁图工具

This commit is contained in:
Li Jianxuan 2014-01-03 02:22:45 +00:00
parent f6b1acc273
commit e2f2b2ae71
1 changed files with 217 additions and 146 deletions

View File

@ -47,6 +47,7 @@ class Thumbnail {
'image/gif' => 'imagegif'
);
}
/**
* 文件方式加载图片
* @param string $image 源图片
@ -71,6 +72,7 @@ class Thumbnail {
trigger_error('不支持'.$dims['mime']."图片类型");
}
}
/**
* 字符串方式加载图片
* @param string $image 字符串
@ -92,6 +94,7 @@ class Thumbnail {
trigger_error("不支持".$mime."图片格式");
}
}
/**
* 生成缩略图
* @param string $file 文件名。如果不为空则储存为文件,否则直接输出到浏览器
@ -104,6 +107,7 @@ class Thumbnail {
return false;
}
}
/**
* 处理缩放
*/
@ -157,6 +161,73 @@ class Thumbnail {
return $this->thumbHeight;
}
static function cut($source_path, $target_width, $target_height){
$source_info = getimagesize($source_path);
$source_width = $source_info[0];
$source_height = $source_info[1];
$source_mime = $source_info['mime'];
$source_ratio = $source_height / $source_width;
$target_ratio = $target_height / $target_width;
// 源图过高
if ($source_ratio > $target_ratio)
{
$cropped_width = $source_width;
$cropped_height = $source_width * $target_ratio;
$source_x = 0;
$source_y = ($source_height - $cropped_height) / 2;
}
// 源图过宽
elseif ($source_ratio < $target_ratio)
{
$cropped_width = $source_height / $target_ratio;
$cropped_height = $source_height;
$source_x = ($source_width - $cropped_width) / 2;
$source_y = 0;
}
// 源图适中
else
{
$cropped_width = $source_width;
$cropped_height = $source_height;
$source_x = 0;
$source_y = 0;
}
switch ($source_mime)
{
case 'image/gif':
$source_image = imagecreatefromgif($source_path);
break;
case 'image/jpeg':
$source_image = imagecreatefromjpeg($source_path);
break;
case 'image/png':
$source_image = imagecreatefrompng($source_path);
break;
default:
return false;
break;
}
$target_image = imagecreatetruecolor($target_width, $target_height);
$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
// 裁剪
imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
// 缩放
imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
header('Content-Type: image/jpeg');
imagejpeg($target_image);
imagedestroy($source_image);
imagedestroy($target_image);
imagedestroy($cropped_image);
}//cute
}
/**