pbootcms的图片裁剪确保无论图片是横图还是竖图,都能居中裁剪
解决方案
-
找到裁剪缩略图的方法:
- 文件位置:
/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);
}
扫码添加技术【解决问题】
专注企业网站建设、网站安全16年。
承接:企业网站建设、网站修改、网站改版、BUG修复、问题处理、二次开发、PSD转HTML、网站被黑、网站漏洞修复等。
专业解决各种疑难杂症,您有任何网站问题都可联系我们技术人员。
本文来自博客园,作者:黄文Rex,转载请注明原文链接:https://www.cnblogs.com/hwrex/p/18439789