| 1 |
<?php |
| 2 |
|
| 3 |
namespace League\Glide\Manipulators; |
| 4 |
|
| 5 |
use Intervention\Image\Image; |
| 6 |
|
| 7 |
/** |
| 8 |
* @property string|null $crop |
| 9 |
*/ |
| 10 |
class Crop extends BaseManipulator |
| 11 |
{ |
| 12 |
/** |
| 13 |
* Perform crop image manipulation. |
| 14 |
* |
| 15 |
* @param Image $image The source image. |
| 16 |
* |
| 17 |
* @return Image The manipulated image. |
| 18 |
*/ |
| 19 |
public function run(Image $image) |
| 20 |
{ |
| 21 |
$coordinates = $this->getCoordinates($image); |
| 22 |
|
| 23 |
if ($coordinates) { |
| 24 |
$coordinates = $this->limitToImageBoundaries($image, $coordinates); |
| 25 |
|
| 26 |
$image->crop( |
| 27 |
$coordinates[0], |
| 28 |
$coordinates[1], |
| 29 |
$coordinates[2], |
| 30 |
$coordinates[3] |
| 31 |
); |
| 32 |
} |
| 33 |
|
| 34 |
return $image; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Resolve coordinates. |
| 39 |
* |
| 40 |
* @param Image $image The source image. |
| 41 |
* |
| 42 |
* @return int[]|null The resolved coordinates. |
| 43 |
* |
| 44 |
* @psalm-return array{0: int, 1: int, 2: int, 3: int}|null |
| 45 |
*/ |
| 46 |
public function getCoordinates(Image $image) |
| 47 |
{ |
| 48 |
if (null === $this->crop) { |
| 49 |
return; |
| 50 |
} |
| 51 |
|
| 52 |
$coordinates = explode(',', $this->crop); |
| 53 |
|
| 54 |
if (4 !== count($coordinates) or |
| 55 |
(!is_numeric($coordinates[0])) or |
| 56 |
(!is_numeric($coordinates[1])) or |
| 57 |
(!is_numeric($coordinates[2])) or |
| 58 |
(!is_numeric($coordinates[3])) or |
| 59 |
($coordinates[0] <= 0) or |
| 60 |
($coordinates[1] <= 0) or |
| 61 |
($coordinates[2] < 0) or |
| 62 |
($coordinates[3] < 0) or |
| 63 |
($coordinates[2] >= $image->width()) or |
| 64 |
($coordinates[3] >= $image->height())) { |
| 65 |
return; |
| 66 |
} |
| 67 |
|
| 68 |
return [ |
| 69 |
(int) $coordinates[0], |
| 70 |
(int) $coordinates[1], |
| 71 |
(int) $coordinates[2], |
| 72 |
(int) $coordinates[3], |
| 73 |
]; |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* Limit coordinates to image boundaries. |
| 78 |
* |
| 79 |
* @param Image $image The source image. |
| 80 |
* @param int[] $coordinates The coordinates. |
| 81 |
* |
| 82 |
* @return int[] The limited coordinates. |
| 83 |
*/ |
| 84 |
public function limitToImageBoundaries(Image $image, array $coordinates) |
| 85 |
{ |
| 86 |
if ($coordinates[0] > ($image->width() - $coordinates[2])) { |
| 87 |
$coordinates[0] = $image->width() - $coordinates[2]; |
| 88 |
} |
| 89 |
|
| 90 |
if ($coordinates[1] > ($image->height() - $coordinates[3])) { |
| 91 |
$coordinates[1] = $image->height() - $coordinates[3]; |
| 92 |
} |
| 93 |
|
| 94 |
return $coordinates; |
| 95 |
} |
| 96 |
} |
| 97 |
|