//php等比例裁剪,或者指定宽高从中心裁剪
public function image_center_crop($source,$despath,$name, $width, $height=0)
{
if(!is_dir($despath))
{
if(!mkdir($despath,0777,true))
{
return array(
'code'=>'-2',"message"=>'错误0003,上传文件失败 ,请联系管理员'
);
}
}
$target = $despath."/".$name;
//if (!file_exists($source)) return false;
/* 根据类型载入图像 */
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
default :
$image = imagecreatefromjpeg($source);
}
if (!isset($image)) return false;
/* 获取图像尺寸信息 */
$source_w = imagesx($image);
$source_h = imagesy($image);
$target_w = $width;
if(!$height){
$height = $source_h/$source_w * $width;
}
$target_h = $height;
/* 计算裁剪宽度和高度 */
$judge = (($source_w / $source_h) > ($target_w / $target_h));
$resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w;
$resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h;
$start_x = $judge ? ($resize_w - $target_w) / 2 : 0;
$start_y = !$judge ? ($resize_h - $target_h) / 2 : 0;
/* 绘制居中缩放图像 */
$resize_img = imagecreatetruecolor($resize_w, $resize_h);
imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h);
$target_img = imagecreatetruecolor($target_w, $target_h);
imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h);
/* 将图片保存至文件 */
//if (!file_exists(dirname($target))) mkdir(dirname($target), 0777, true);
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
$target .= ".jpg";
imagejpeg($target_img, $target);
break;
case IMAGETYPE_PNG:
$target .= ".png";
imagepng($target_img, $target);
break;
case IMAGETYPE_GIF:
$target .= ".gif";
imagegif($target_img, $target);
break;
default :
$target .= ".jpg";
imagejpeg($target_img, $target);
}
return array(
'code'=>'1','message'=>$target
);
}
php 图片裁剪
最新推荐文章于 2024-05-16 10:51:26 发布