PHP GD - 围绕任何给定点裁剪图像

时间:2014-09-15 13:33:10

标签: php gd center crop

我有以下脚本使用php' s gd成功裁剪并在中心点成像:

list($source_width, $source_height, $source_type) = getimagesize($img_path);

define('IMAGE_WIDTH', 200);
define('IMAGE_HEIGHT', 300);

$ratio = $source_width / $source_height;
$desired_aspect_ratio = IMAGE_WIDTH / IMAGE_HEIGHT;

if ($ratio > $desired_aspect_ratio) {
    $temp_height = IMAGE_HEIGHT;
    $temp_width = ( int ) (IMAGE_HEIGHT * $ratio);
} else {
    $temp_width = IMAGE_WIDTH;
    $temp_height = ( int ) (IMAGE_WIDTH / $ratio);
}

$x = ($temp_width - IMAGE_WIDTH) / 2;
$y = ($temp_height - IMAGE_HEIGHT) / 2;

$cropped = imagecreatetruecolor(IMAGE_WIDTH, IMAGE_HEIGHT);
imagecopy(
    $cropped,
    $temp,
    0, 0,
    $x, $y,
    IMAGE_WIDTH, IMAGE_HEIGHT
);

而不是中心的这个:

$x = ($temp_width - IMAGE_WIDTH) / 2;
$y = ($temp_height - IMAGE_HEIGHT) / 2;

在我的网站上,用户可以选择主要焦点'图像,我会在其周围裁剪图像。重点将以百分比形式提供。我已经有了百分比和客户选择的方式,我只需要采取这些值并围绕它们进行裁剪。可以这样做吗?例如,如果我希望我的图像在点周围被裁剪,如下图所示:

enter image description here

1 个答案:

答案 0 :(得分:3)

以下功能可以做你想要的。

  • 仅传递第一个参数将输出您现在拥有的内容:源图像的中间裁剪为200px / 200px。
  • 第二个和第三个参数允许您根据需要指定裁剪中心的X / Y百分比坐标。
  • 第四个和第五个参数允许您设置裁剪图像的大小。

(请注意,这假定为PNG,但如果需要,您应该能够轻松地对其他格式进行调整。)

function crop($file, $cropX = 50, $cropY = 50, $cropW = 200, $cropH = 200)
{
    $src = imagecreatefrompng($file);
    $dest = imagecreatetruecolor($cropW, $cropH);

    list($src_w, $src_h) = getimagesize($file);

    // calculate x/y coordinates for crop from supplied percentages.
    $src_x = (($src_w / 100) * $cropX) - ($cropW / 2);
    $src_y = (($src_h / 100) * $cropY) - ($cropH / 2);

    imagecopy($dest, $src, 0, 0, $src_x, $src_y, $src_w, $src_h);

    imagedestroy($src);

    return $dest;
}

示例用法(将X的裁剪焦点设置为70%):

$img = crop('test.png', 70);
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);