Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

php - Max crop area for a given image and aspect ratio

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...