从中心 PHP 裁剪图像 [英] Crop Image From Center PHP
问题描述
我想从中心裁剪 200 * 130 大小的图像,要裁剪的图像大小可能会有所不同,如果图像较小,我们不会裁剪它,我知道如何在这部分检查高度和图像,但有点撞到从图像中间裁剪的东西因为我不知道如何将中心保持为裁剪点而不是向外裁剪
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
推荐答案
从 4.3.6 版本开始,GD 与所有 PHP 安装捆绑在一起,所以您有机会拥有它.
GD comes bundled with all PHP installations from version 4.3.6 onwards so chances are, you have it.
这是您需要采取的步骤...
Here's the steps you need to take...
- 使用 GD
imagecreatefrom*()
之一创建图像资源> 功能.您使用的那个取决于您正在处理的图像类型 - 使用
imagesx()
和imagesy()
- 使用以下算法确定您的裁剪坐标并使用
imagecopy()
进行裁剪
查找裁剪坐标
$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);
随意使用我的图像处理类,它应该使某些方面更容易 - https://gist.github.com/880506
Feel free to use my image manipulation class, it should make some aspects much easier - 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');
这篇关于从中心 PHP 裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!