为了实现居中裁剪图片的功能,可以通过修改 cut_img 方法来实现。具体步骤如下:

  1. 定位并修改 cut_img 方法

    • 文件位置:/core/function/file.php
    • 修改 cut_img 方法,使其支持居中裁剪。
  2. 修改后的 cut_img 方法

    • 在裁剪前先进行缩放处理,然后从中心位置裁剪。

以下是修改后的 cut_img 方法代码:

php
 
// 剪切图片
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 IMAGETYPE_GIF:
$img = imagecreatefromgif($src_image);
break;
case IMAGETYPE_JPEG:
$img = imagecreatefromjpeg($src_image);
break;
case IMAGETYPE_PNG:
$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 == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {
$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, $new_width, $new_height);

check_dir(dirname($out_image), true); // 检查输出目录

switch ($type) {
case IMAGETYPE_GIF:
imagegif($new_img, $out_image, $img_quality);
break;
case IMAGETYPE_JPEG:
imagejpeg($new_img, $out_image, $img_quality);
break;
case IMAGETYPE_PNG:
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;
}

使用方法

使用 {pboot:list} 标签时,添加 width 和 height 参数来生成居中裁剪的图片:

html
 
{pboot:list scode=*}
<a href="[list:link]"><img src="[list:ico width=600 height=400]" alt="[list:title]" /></a>
{/pboot:list}

说明

  1. width 和 height 参数

    • 设置图片的宽度和高度,裁剪后的图片将居中裁剪为指定大小。
  2. 居中裁剪

    • 通过计算裁剪起始点 $start_x 和 $start_y,确保裁剪从中心位置开始。

通过以上修改,你可以实现居中裁剪图片的功能,无论图片是横图还是竖图,都能得到理想的裁剪效果。