在使用PbootCms模板时,默认的图片裁剪功能是从左上角开始进行裁剪。我们可以通过width、height、maxwidth、maxheight等参数对图片大小进行调整。
然而,有时候默认的裁剪方式并不能满足我们的需求。例如,在处理多人物合影时,PbootCms默认从左上角裁剪,可能会导致重要的人物(如C位)被裁掉,这显然是不可接受的。
为了解决这个问题,我们可以优化图片裁剪功能,使其能够简单快捷地生成理想的图片。本文将介绍如何实现无论横图还是竖图都居中裁剪的效果。
下面是具体的解决方案:
首先,我们需要找到裁剪缩略图的方法。
文件位置:/core/function/file.php
搜索方法名:function cut_img,该方法大约位于447行。
接下来,我们将对该方法进行优化。以下是优化后的代码:
// 剪切图片
function cut_img($src_image, $out_image = null, int $new_width = null, int $new_height = null, $img_quality = 90)
{
// 输出地址
if (! $out_image)
$out_image = $src_image;
// 读取配置文件设置
if (! $new_width && ! $new_height)
return;
// 获取图片属性
list ($width, $height, $type, $attr) = getimagesize($src_image);
switch ($type) {
case 1:
$img = imagecreatefromgif($src_image);
break;
case 2:
$img = imagecreatefromjpeg($src_image);
break;
case 3:
$img = imagecreatefrompng($src_image);
break;
}
// 不限定是等比例缩放
if (! $new_width) {
$new_width = floor($width * ($new_height / $height));
}
if (! $new_height) {
$new_height = floor($height * ($new_width / $width));
}
// 创建画布
$new_img = imagecreatetruecolor($new_width, $new_height);
// 创建透明画布,避免黑色
if ($type == 1 || $type == 3) {
$color = imagecolorallocate($new_img, 255, 255, 255);
imagefill($new_img, 0, 0, $color);
imagecolortransparent($new_img, $color);
}
// 先缩放
$scale = max($new_width / $width, $new_height / $height);
$scale_width = floor($scale * $width);
$scale_height = floor($scale * $height);
$scale_img = imagecreatetruecolor($scale_width, $scale_height); // 创建画布
if(function_exists("ImageCopyResampled")) {
imagecopyresampled($scale_img, $img, 0, 0, 0, 0, $scale_width, $scale_height, $width, $height);
} else {
imagecopyresized($scale_img, $img, 0, 0, 0, 0, $scale_width, $scale_height, $width, $height);
}
//再裁剪
$start_x = ($scale_width - $new_width) / 2;
$start_y = ($scale_height - $new_height) / 2;
//拷贝剪切的图像数据到画板,生成剪切图像
imagecopy($new_img, $scale_img, 0, 0, $start_x, $start_y, $scale_width, $scale_height);
check_dir(dirname($out_image), true); // 检查输出目录
switch ($type) {
case 1:
imagegif($new_img, $out_image, $img_quality);
break;
case 2:
imagejpeg($new_img, $out_image, $img_quality);
break;
case 3:
imagepng($new_img, $out_image, $img_quality / 10); // $quality参数取值范围0-99 在php 5.1.2之后变更为0-9
break;
default:
imagejpeg($new_img, $out_image, $img_quality);
}
imagedestroy($new_img);
imagedestroy($img);
return true;
}
小伙伴们可以直接用上述代码替换原有的cut_img方法。
接下来是使用方法:
以上代码可以直接生成600*400像素的居中裁剪过的图片。
举个例子:如果需要在列表中输出图片,可以按照上述代码进行操作。
通过这种方法,我们可以轻松实现图片的居中裁剪,无论是横图还是竖图都能得到理想的效果。
至此,任务完成!