Max crop area for a given image and aspect ratio

情到浓时终转凉″ 提交于 2019-12-30 11:25:11

问题


Is there any PHP/GD function that can calculate this:

Input: image width, image height and an aspect ratio to honor. Output: the width/height of the max centered crop that respects the given aspect ratio (despite image original aspect ratio).

Example: image is 1000x500, a.r. is 1.25: max crop is 625x500. image is 100x110, max crop is: 80x110.


回答1:


There is no function that calculates this because it's elementary math:

$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.



来源:https://stackoverflow.com/questions/8541380/max-crop-area-for-a-given-image-and-aspect-ratio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!