PHP图像居中裁剪函数实现
本实例展示了一个由PHP编写的自定义图像居中裁剪功能,供开发者参考使用。
实现图像居中裁剪的核心逻辑如下:
第一步是对图像进行缩放处理,确保缩放后的画面能够完全覆盖指定的裁减区域(参考函数:imagecopyresampled — 重采样拷贝部分图像并调整大小)。
第二步是将缩放后的图像精准放置在裁减区域的中心位置(参考函数:imagecopy — 拷贝图像的一部分)。
第三步是执行裁减操作并将最终图像保存(参考函数:imagejpeg | imagepng | imagegif — 输出图象到浏览器或文件)。
以下是具体的实现代码:
//==================缩放裁剪函数====================
/**
* 居中裁剪图片
* @param string $source [原图路径]
* @param int $width [设置宽度]
* @param int $height [设置高度]
* @param string $target [目标路径]
* @return bool [裁剪结果]
*/
function image_center_crop($source, $width, $height, $target)
{
if (!file_exists($source)) return false;
/* 根据类型载入图像 */
switch (exif_imagetype($source)) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source);
break;
}
if (!isset($image)) return false;
/* 获取图像尺寸信息 */
$target_w = $width;
$target_h = $height;
$source_w = imagesx($image);
$source_h = imagesy($image);
/* 计算裁剪宽度和高度 */
$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:
imagejpeg($target_img, $target);
break;
case IMAGETYPE_PNG:
imagepng($target_img, $target);
break;
case IMAGETYPE_GIF:
imagegif($target_img, $target);
break;
}
// return boolval(file_exists($target));//PHP5.5以上可用boolval()函数获取返回的布尔值
return file_exists($target)?true:false;//兼容低版本PHP写法
}
//==================函数使用方式====================
// 原始图片的路径
$source = '../source/img/middle.jpg';
$width = 480; // 裁剪后的宽度
$height = 480;// 裁剪后的高度
// 裁剪后的图片存放目录
$target = '../source/temp/resize.jpg';
// 裁剪后保存到目标文件夹
if (image_center_crop($source, $width, $height, $target)) {
echo "原图1440*900为:";
echo "";
echo "修改后图片480*480为:";
}
运行效果演示:
原始图片尺寸为1440*900,显示为
处理后生成的图片尺寸为480*480,显示为:
同理,若需生成480*320、800*600等其他尺寸的图片,仅需调整相应的参数即可。
附:代码测试过程中遇到的问题记录
常见报错信息:call an undefined function exif_imagetype()
解决该问题的方法如下:
首先需要在配置中打开扩展 extension=php_exif.dll
随后将extension=php_mbstring.dll 的配置项放置于extension=php_exif.dll 之前
另外说明:boolval() 函数仅在PHP5.5及以上版本中可用。为了兼容较低版本的PHP环境,本文测试代码中采用了以下语句作为替代方案:
return file_exists($target)?true:false;
PS:此外,推荐几款相关的在线图片处理工具供参考:
在线图片格式转换(jpg/bmp/gif/png)工具: 点击使用
在线图片旋转、裁剪与标注:点击使用
ICO图标在线生成工具: 点击使用
希望上述内容能对各位在PHP程序设计方面有所帮助。