4

これを計算できるPHP/GD関数はありますか?

入力:画像の幅、画像の高さ、アスペクト比を尊重します。出力:指定されたアスペクト比を尊重する最大中心クロップの幅/高さ(画像の元のアスペクト比にもかかわらず)。

例:画像は1000x500、arは1.25:最大トリミングは625x500です。画像は100x110、最大トリミングは80x110です。

4

2 に答える 2

10

これは初歩的な数学であるため、これを計算する関数はありません。

$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;
}

実際の動作をご覧ください

于 2011-12-16T23:46:37.913 に答える
2

@Jon回答の拡張として、PHP-GDライブラリでのこのアプローチの実装を次に示します。

/**
 * 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;
}
于 2020-08-09T11:55:51.033 に答える