本文实例讲述了PHP实现的自定义图像居中裁剪函数。分享给大家供大家参考,具体如下:
图像居中裁减的大致思路:
1.首先将图像进行缩放,使得缩放后的图像能够恰好覆盖裁减区域。(imagecopyresampled — 重采样拷贝部分图像并调整大小)
2.将缩放后的图像放置在裁减区域中间。(imagecopy — 拷贝图像的一部分)
3.裁减图像并保存。(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)