给定图像和纵横比的最大裁剪区域
Posted
技术标签:
【中文标题】给定图像和纵横比的最大裁剪区域【英文标题】:Max crop area for a given image and aspect ratio 【发布时间】:2011-12-16 23:28:21 【问题描述】:是否有任何 php/GD 函数可以计算这个:
输入:图像宽度、图像高度和要遵守的纵横比。输出: 尊重给定纵横比的最大居中裁剪的宽度/高度 (尽管图像原始纵横比)。
示例:图片为 1000x500,a.r.为 1.25:最大裁剪为 625x500。图片为 100x110,最大裁剪为:80x110。
【问题讨论】:
【参考方案1】:没有计算这个的函数,因为它是初等数学:
$imageWidth = 1000;
$imageHeight = 500;
$ar = 1.25;
if ($ar < 1) // "tall" crop
$cropWidth = min($imageHeight * $ar, $imageWidth);
$cropHeight = $cropWidth / $ar;
else // "wide" or square crop
$cropHeight = min($imageWidth / $ar, $imageHeight);
$cropWidth = $cropHeight * $ar;
See it in action.
【讨论】:
谢谢。我花了几分钟的时间,得到了类似你的代码的东西(但你的解决方案更优雅)。是的,基本但有用。 非常好的解决方案。尽管当我试图理解它时我的大脑完全一片空白,但它就像一种魅力。 @ScooterDaraf:已修复。【参考方案2】:作为@Jon 的answer 的扩展,这是PHP-GD library 中这种方法的实现
/**
* Crops image by taking largest area rectangle from center of image so that the desired aspect ratio is realized.
* @param resource $src_image image resource to be cropped
* @param float $required_aspect_ratio Desired aspect ratio to be achieved via cropping
* @return resource cropped image
*/
public function withCenterCrop($src_image, float $required_aspect_ratio)
$crr_width = imagesx($src_image);
$crr_height = imagesy($src_image);
$crr_aspect_ratio = $crr_width / $crr_height;
$cropped_image = null;
if ($crr_aspect_ratio < $required_aspect_ratio)
// current image is 'taller' (than what we need), it must be trimmed off from top & bottom
$new_width = $crr_width;
$new_height = $new_width / $required_aspect_ratio;
// calculate the value of 'y' so that central portion of image is cropped
$crop_y = (int) (($crr_height - $new_height) / 2);
$cropped_image = imagecrop(
$src_image,
['x' => 0, 'y' => $crop_y, 'width' => $new_width, 'height' => $new_height]
);
else
// current image is 'wider' (than what we need), it must be trimmed off from sides
$new_height = $crr_height;
$new_width = $new_height * $required_aspect_ratio;
// calculate the value of 'x' so that central portion of image is cropped
$crop_x = (int) (($crr_width - $new_width) / 2);
$cropped_image = imagecrop(
$src_image,
['x' => $crop_x, 'y' => 0, 'width' => $new_width, 'height' => $new_height]
);
return $cropped_image;
【讨论】:
以上是关于给定图像和纵横比的最大裁剪区域的主要内容,如果未能解决你的问题,请参考以下文章