<?php
//$source_path 源图片地址
//$cut_h 裁剪高度
//$cut_type 裁剪类型 1像素 2百分比
//$limit_w 图片宽度小于$limit_w不处理
//$limit_w 图片高度小于$limit_w不处理
function cutImage($source_path, $cut_h, $cut_type,$limit_w,$limit_h){
//兼容.webp图片
if(preg_match('/\.webp/',$source_path)){
$source_image = imagecreatefromwebp($source_path); //创建Webp图像资源
$source_width = imagesx($source_image); //获取宽
$source_height = imagesy($source_image); //获取高
}else{
//获取图像信息
$source_info = getimagesize($source_path);
$source_width = $source_info[0]; //图象宽
$source_height = $source_info[1]; //图象高
$source_mime = $source_info['mime']; //图象类型 例:image/png
}
//图片尺寸太小时不处理
if($source_width<=$limit_w || $source_height<=$limit_h || $cut_h >$source_height){
return $source_path;
}
//根据图片类型获取图片资源
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:
break;
}
//创建新图象
$dst_image_w = $source_width;
if($cut_type == 2){
$dst_image_h = $source_height - $source_height*($cut_h*0.01)/2;
}else{
$dst_image_h = $source_height-$cut_h/2;
}
$dst_image = imagecreatetruecolor($dst_image_w,$dst_image_h);
//图像裁减给新图象
// bool imagecopyresampled ( $dst_image , $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
// dst_image 目标图象连接资源。
// src_image 源图象连接资源。
// dst_x 目标 X 坐标点。
// dst_y 目标 Y 坐标点。
// src_x 源的 X 坐标点。
// src_y 源的 Y 坐标点。
// dst_w 目标宽度。
// dst_h 目标高度。
// src_w 源图象的宽度。
// src_h 源图象的高度。
imagecopyresampled($dst_image, $source_image, 0, 0, 0, 0, $dst_image_w, $dst_image_h, $source_width, $dst_image_h);
//生成输出新图象
$ot = pathinfo($source_path, PATHINFO_EXTENSION);
$otfunc = 'image' . ($ot == 'jpg' ? 'jpeg' : $ot);
$otfunc($dst_image,$source_path);
//关闭资源
imagedestroy($source_image);
imagedestroy($dst_image);
return $source_path;
}
$filename = "./demo.jpg";
$img = cutImage($filename,10,1,10,10);
echo '<img src="'.$img.'"/>';
?>