我需要计算给定 xy 坐标的图像裁剪位置

I need to calculate where to crop an image given x&y coordinates

我需要在我的应用程序的原始图像中间裁剪图像,为了制作裁剪,我需要提供 (x,y) 坐标,这使得裁剪从给定坐标开始。
所以我明白为了计算 x 和 y 我需要对两者应用相同的计算。
请帮助我了解我需要计算 X 坐标以裁剪图像。

originalWidth = 1200   
newWidth = 600   
startCroopAt = ?

[x,y]

Image::crop(Yii::getAlias('@app/web/images/tmp/tmp_'.$name), $newWidth, $newHeight, [0,0])
        ->save(Yii::getAlias($path."/".$name), ['quality' => 80]);

感谢您帮助解释。

startCroopAt = (原始宽度 - 新宽度) / 2

newPosition = previousPosition + startCroopAt

简而言之,您应该计算缩减指数以计算新位置,即通过用新宽度减去旧宽度来计算。 由于图像裁剪必须居中,因此您将索引除以二以模拟某种填充。 这样,newPosition 将是从裁剪前的初始位置开始的位移索引。

计算高度时采用相同的程序,但在 y 轴和宽度上使用新的高度。

希望对您有所帮助。

数值示例为。

originalWidth = 1200   
newWidth = 600   
startCroopAt = (1200 - 600)/2 = 300
newPosition = 0 + 300

我猜 previousPosition 是原点,但如果存在图像位移,使用 previousPosition 即可解决。

我使用了[Imagine]图片库,可以更轻松的完成图片裁剪。我喜欢它,因为它与文件类型无关,并且支持 透明 PNGs。此函数还使用指定的宽度和高度调整图像的大小。

$cropheight = $bottom - $top;
$cropwidth  = $right - $left;
$target = "./images/cropped/";

$imagine->open($path)
    ->crop(new Point($top, $left), new Box($cropheight,$cropwidth))
    ->resize(new Box($width, $height))
    ->save($target);

我定义了裁剪时使用的最重要的参数。我正在使用大约 1000x1000 的图像,并想在它的中心大致裁剪。

$uri="http://./smile.jpg";

$top = 90;
$left = 40;
$bottom = 800;
$right = 500;

$width = 920;
$height = 500;