请看实例
/**
* @todo 图片裁剪
* @param type $imagepath 初始图片路径
* @param type $savepath 保存的路径位
* @param type $newwidth 传入-图像宽
* @param type $newheight 传入-图像高
* @return string
*/
function imageTranscoding($imagepath, $savepath, $newwidth, $newheight) {
$new_width = intval($newwidth);
$new_height = intval($newheight);
if ($new_width < 1 || $new_height < 1) return "参数错误";
if (!file_exists($imagepath)) return "文件不存在";
$type = exif_imagetype($imagepath);
$support_type = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
if (!in_array($type, $support_type, true)) return "文件类型不支持";
switch ($type)
{
case IMAGETYPE_JPEG :
$src_img = imagecreatefromjpeg($imagepath);
break;
case IMAGETYPE_PNG :
$src_img = imagecreatefrompng($imagepath);
break;
case IMAGETYPE_GIF :
$src_img = imagecreatefromgif($imagepath);
break;
}
$w = imagesx($src_img);
$h = imagesy($src_img);
$ratio_w = 1.0 * $new_width / $w;
$ratio_h = 1.0 * $new_height / $h;
$ratio = 1.0;
if (($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
if ($ratio_w < $ratio_h) $ratio = $ratio_h; else $ratio = $ratio_w;
$inter_w = (int) ($new_width / $ratio);
$inter_h = (int) ($new_height / $ratio);
$inter_img = imagecreatetruecolor($inter_w, $inter_h);
imagecopy($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h);
//更改PHP的内存限制
ini_set('memory_limit', '18M');
$new_img = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height, $inter_w, $inter_h);
switch ($type)
{
case IMAGETYPE_JPEG :
imagejpeg($new_img, $savepath, 100);
break;
case IMAGETYPE_PNG :
imagepng($new_img, $savepath, 100);
break;
case IMAGETYPE_GIF :
imagegif($new_img, $savepath, 100);
break;
}
}
else {
$ratio = $ratio_h > $ratio_w ? $ratio_h : $ratio_w;
$inter_w = (int) ($w * $ratio);
$inter_h = (int) ($h * $ratio);
$inter_img = imagecreatetruecolor($inter_w, $inter_h);
imagecopyresampled($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h, $w, $h);
$new_img = imagecreatetruecolor($new_width, $new_height);
imagecopy($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height);
switch ($type)
{
case IMAGETYPE_JPEG :
imagejpeg($new_img, $savepath, 100);
break;
case IMAGETYPE_PNG :
imagepng($new_img, $savepath, 100);
break;
case IMAGETYPE_GIF :
imagegif($new_img, $savepath, 100);
break;
default :
break;
}
}
}
$this->imageTranscoding("test2.jpeg", "/test2_300x200.jpeg", 300, 200);