从中心 PHP 裁剪图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6891352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:33:35  来源:igfitidea点击:

Crop Image From Center PHP

phpimage-processing

提问by June

I want to crop an image from the center in the size 200 * 130 the image to be cropped may vary in size, if the image is smaller we wont crop it i know how to this part where i can check height and with of image but kind of struck into the thing of cropping from the middle of the image As i cant figure it out how to keep the center as crop point and than outward crop it

我想从中心裁剪 200 * 130 大小的图像,要裁剪的图像大小可能会有所不同,如果图像较小,我们不会裁剪它,我知道如何在这部分检查图像的高度和图像,但是有点影响从图像中间裁剪的东西 因为我不知道如何将中心保持为裁剪点而不是向外裁剪它

回答by Phil

GD comes bundled with all PHP installations from version 4.3.6 onwards so chances are, you have it.

从 4.3.6 版开始,GD 与所有 PHP 安装捆绑在一起,所以您有机会拥有它。

Here's the steps you need to take...

这是您需要采取的步骤...

  1. Create an image resource using one of the GD imagecreatefrom*()functions. The one you use depends on the type of image you're dealing with
  2. Determine the image dimensions using imagesx()and imagesy()
  3. Determine your crop coordinates using the following algorithm and crop using imagecopy()
  1. 使用 GDimagecreatefrom*()函数之一创建图像资源。您使用的那个取决于您正在处理的图像类型
  2. 使用imagesx()和确定图像尺寸imagesy()
  3. 使用以下算法确定您的裁剪坐标并使用裁剪 imagecopy()

Find crop coordinates

查找裁剪坐标

$width  = imagesx($img);
$height = imagesy($img);
$centreX = round($width / 2);
$centreY = round($height / 2);

$cropWidth  = 200;
$cropHeight = 130;
$cropWidthHalf  = round($cropWidth / 2); // could hard-code this but I'm keeping it flexible
$cropHeightHalf = round($cropHeight / 2);

$x1 = max(0, $centreX - $cropWidthHalf);
$y1 = max(0, $centreY - $cropHeightHalf);

$x2 = min($width, $centreX + $cropWidthHalf);
$y2 = min($height, $centreY + $cropHeightHalf);

Feel free to use my image manipulation class, it should make some aspects much easier - https://gist.github.com/880506

随意使用我的图像处理类,它应该使某些方面更容易 - https://gist.github.com/880506

$im = new ImageManipulator('/path/to/image');
$centreX = round($im->getWidth() / 2);
$centreY = round($im->getHeight() / 2);

$x1 = $centreX - 100;
$y1 = $centreY - 65;

$x2 = $centreX + 100;
$y2 = $centreY + 65;

$im->crop($x1, $y1, $x2, $y2); // takes care of out of boundary conditions automatically
$im->save('/path/to/cropped/image');

回答by totymedli

Image crop with configurable alignment

具有可配置对齐的图像裁剪

Here is a native implementation of a function (called cropAlign) that can crop an image to a given width and height with alignto the 9 standard points (4 edges, 4 corners, 1 center).

这是一个函数(称为cropAlign)的本机实现,它可以将图像裁剪为给定的宽度和高度,并对齐9 个标准点(4 个边、4 个角、1 个中心)。

Alignment points

对齐点

Just pass the image, the desired size of the crop, and the alignment on the two axis (you can use left, center, rightor top, middle, bottomirregardless from the axis) for the cropAlignfunction.

只需传递图像、所需的裁剪尺寸以及两个轴上的对齐(您可以使用left, center,righttop, middlebottom不管轴是否来自该cropAlign函数)。

Specification

规格

Description

cropAlign(resource $image, int $width, int $height, string $horizontalAlign = 'center', string $verticalAlign = 'middle')

Parameters

  • image: An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().
  • width: Width of the final cropped image.
  • height: Height of the final cropped image.
  • horizontalAlign: Where the crop should be aligned along the horizontal axis. Possible values are: left/top, center/middle, right/bottom.
  • verticalAlign: Where the crop should be aligned along the vertical axis. Possible values are: left/top, center/middle, right/bottom.

Return Values

Return cropped image resource on success or FALSEon failure. This comes from imagecrop().

描述

cropAlign(resource $image, int $width, int $height, string $horizontalAlign = 'center', string $verticalAlign = 'middle')

参数

  • image:图像资源,由图像创建函数之一返回,例如imagecreatetruecolor().
  • width:最终裁剪图像的宽度。
  • height:最终裁剪图像的高度。
  • horizontalAlign:裁剪应沿水平轴对齐的位置。可能的值为:left/ topcenter/ middleright/ bottom
  • verticalAlign:裁剪应沿垂直轴对齐的位置。可能的值为:left/ topcenter/ middleright/ bottom

返回值

成功或FALSE失败时返回裁剪的图像资源。这来自imagecrop().

Source code

源代码

function cropAlign($image, $cropWidth, $cropHeight, $horizontalAlign = 'center', $verticalAlign = 'middle') {
    $width = imagesx($image);
    $height = imagesy($image);
    $horizontalAlignPixels = calculatePixelsForAlign($width, $cropWidth, $horizontalAlign);
    $verticalAlignPixels = calculatePixelsForAlign($height, $cropHeight, $verticalAlign);
    return imageCrop($image, [
        'x' => $horizontalAlignPixels[0],
        'y' => $verticalAlignPixels[0],
        'width' => $horizontalAlignPixels[1],
        'height' => $verticalAlignPixels[1]
    ]);
}

function calculatePixelsForAlign($imageSize, $cropSize, $align) {
    switch ($align) {
        case 'left':
        case 'top':
            return [0, min($cropSize, $imageSize)];
        case 'right':
        case 'bottom':
            return [max(0, $imageSize - $cropSize), min($cropSize, $imageSize)];
        case 'center':
        case 'middle':
            return [
                max(0, floor(($imageSize / 2) - ($cropSize / 2))),
                min($cropSize, $imageSize),
            ];
        default: return [0, $imageSize];
    }
}

Example usage

示例用法

Here are some crop examples using this imageof the Utah teapot.

以下是一些使用犹他州茶壶图像的作物示例。

$im = imagecreatefrompng('https://i.stack.imgur.com/NJcML.png');
imagePng(cropAlign($im, 200, 250, 'center', 'middle'));
imagePng(cropAlign($im, 300, 150, 'left', 'top'));
imagePng(cropAlign($im, 1000, 250, 'right', 'middle'));

Input

输入

Example input: Utah teapot

示例输入:犹他州茶壶

Output

输出

cropAlign($im, 200, 250, 'center', 'middle')

Output #1

输出 #1

cropAlign($im, 300, 150, 'left', 'top')

Output #2

输出#2

cropAlign($im, 1000, 250, 'right', 'middle')

Output #3

输出 #3

回答by Ethan SK

Jeez, why are you doing it the hard way? Just simply set the x and y positions as the amount to crop / 2

天哪,你为什么要这么艰难?只需简单地将 x 和 y 位置设置为要裁剪的数量 / 2

   $imageSize = getimagesize('thumbnail.png');

$croppedImage = imagecrop(imagecreatefrompng('thumbnail.png'), ['x' => 0, 'y' => ($imageSize[1]-$imageSize[0]*(9/16))/2, 'width' => $imageSize[0], 'height' =>  $imageSize[0]*(9/16)]);

notice how I used my $imageSize[0]*(9/16), which is the amount i am cropping by in the y direction, and i subtracted that from the original image height to find crop amount, then divided by 2. If you want to do the same for width, simply follow the same steps.

请注意我如何使用 $imageSize[0]*(9/16),这是我在 y 方向上裁剪的数量,我从原始图像高度中减去它以找到裁剪数量,然后除以 2。如果你想对宽度做同样的事情,只需按照相同的步骤。

回答by P. R. Ribeiro

This might help you.

这可能对你有帮助。

function cropCentered($img, $w, $h)
{
  $cx = $img->getWidth() / 2;
  $cy = $img->getHeight() / 2;
  $x = $cx - $w / 2;
  $y = $cy - $h / 2;
  if ($x < 0) $x = 0;
  if ($y < 0) $y = 0;
  return $img->crop($x, $y, $w, $h);
}

I'm assuming you're using the GD library. $img is a GD image, $w and $h are width and height, respectively, you want your new image to have. In your case, $w = 200, $h = 130.

我假设您正在使用 GD 库。$img 是 GD 图像,$w 和 $h 分别是宽度和高度,您希望新图像具有。在您的情况下,$w = 200,$h = 130。