|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Jonasdamher\Simplifyimage\Utils; |
|
6
|
|
|
|
|
7
|
|
|
use Jonasdamher\Simplifyimage\Core\ResponseHandler; |
|
8
|
|
|
use Jonasdamher\Simplifyimage\Utils\Position; |
|
9
|
|
|
use Jonasdamher\Simplifyimage\Utils\Shape; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Image crop, position and shape crop. |
|
13
|
|
|
*/ |
|
14
|
|
|
class Crop |
|
15
|
|
|
{ |
|
16
|
|
|
|
|
17
|
|
|
public Position $position; |
|
18
|
|
|
public Shape $shape; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct() |
|
21
|
|
|
{ |
|
22
|
|
|
$this->position = new Position; |
|
23
|
|
|
$this->shape = new Shape; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
private function dimensions($image): array |
|
27
|
|
|
{ |
|
28
|
|
|
return [ |
|
29
|
|
|
'x' => imagesx($image), |
|
30
|
|
|
'y' => imagesy($image) |
|
31
|
|
|
]; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
private function cropped($image, array $position, array $shape) |
|
35
|
|
|
{ |
|
36
|
|
|
try { |
|
37
|
|
|
$crop = imagecrop($image, [ |
|
38
|
|
|
'x' => $position['x'], |
|
39
|
|
|
'y' => $position['y'], |
|
40
|
|
|
'width' => $shape['x'], |
|
41
|
|
|
'height' => $shape['y'] |
|
42
|
|
|
]); |
|
43
|
|
|
|
|
44
|
|
|
if (!$crop) { |
|
45
|
|
|
throw new \Exception('image cropping error'); |
|
46
|
|
|
} |
|
47
|
|
|
} catch (\Exception $e) { |
|
48
|
|
|
$crop = $image; |
|
49
|
|
|
ResponseHandler::fail($e->getMessage()); |
|
50
|
|
|
} finally { |
|
51
|
|
|
return $crop; |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
private function verifyIfThePropertyChange(): bool |
|
56
|
|
|
{ |
|
57
|
|
|
return $this->shape->get() != 'default'; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function modify($image) |
|
61
|
|
|
{ |
|
62
|
|
|
try { |
|
63
|
|
|
if ($this->verifyIfThePropertyChange()) { |
|
64
|
|
|
$finalImage = $image; |
|
65
|
|
|
$dimensions = $this->dimensions($finalImage); |
|
66
|
|
|
|
|
67
|
|
|
$position = $this->position->new($dimensions); |
|
68
|
|
|
|
|
69
|
|
|
$imageWithShape = $this->shape->modify($finalImage, $position, $dimensions); |
|
70
|
|
|
|
|
71
|
|
|
if (is_array($imageWithShape)) { |
|
72
|
|
|
$image = $this->cropped($finalImage, $position, $imageWithShape); |
|
73
|
|
|
} else if (is_resource($imageWithShape)) { |
|
74
|
|
|
$image = $imageWithShape; |
|
75
|
|
|
} else { |
|
76
|
|
|
throw new \Exception('Could not shape image'); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
} catch (\Exception $e) { |
|
80
|
|
|
ResponseHandler::fail($e->getMessage()); |
|
81
|
|
|
} finally { |
|
82
|
|
|
return $image; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|