从中心PHP裁剪图像 [英] Crop Image From Center PHP

查看:204
本文介绍了从中心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

推荐答案

GD与4.3.6版本以后的所有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...


  1. 使用GD之一创建图像资源 imagecreatefrom *() 个函数。您使用的图像取决于您正在处理的图像类型

  2. 使用 imagesx() imagesy()

  3. 使用以下算法确定裁剪坐标并使用 imagecopy()

  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()

查找裁剪坐标

$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆