解决方案
-
找到裁剪缩略图的方法:
- 文件位置:
/core/function/file.php
- 搜索:
function cut_img
,大约在447行
- 文件位置:
-
优化
cut_img
方法:- 实现居中裁剪功能
优化代码
以下是优化后的cut_img
函数代码:
// 剪切图片
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;default:return;}// 计算裁剪区域$crop_width = min($width, $new_width);$crop_height = min($height, $new_height);$crop_x = intval(($width - $crop_width) / 2); // 居中裁剪$crop_y = intval(($height - $crop_height) / 2); // 居中裁剪// 创建新画布$new_img = imagecreatetruecolor($new_width, $new_height);// 创建透明画布,避免黑色背景if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {imagealphablending($new_img, false);imagesavealpha($new_img, true);$color = imagecolorallocatealpha($new_img, 255, 255, 255, 127);imagefilledrectangle($new_img, 0, 0, $new_width, $new_height, $color);}// 裁剪并缩放imagecopyresampled($new_img, $img, 0, 0, $crop_x, $crop_y, $new_width, $new_height, $crop_width, $crop_height);// 保存新图片switch ($type) {case IMAGETYPE_GIF:imagegif($new_img, $out_image);break;case IMAGETYPE_JPEG:imagejpeg($new_img, $out_image, $img_quality);break;case IMAGETYPE_PNG:imagepng($new_img, $out_image);break;}// 释放资源imagedestroy($img);imagedestroy($new_img);
}