|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @package Application Utils |
|
4
|
|
|
* @subpackage ImageHelper |
|
5
|
|
|
* @see \AppUtils\ImageHelper\ImageTrimmer |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
declare(strict_types=1); |
|
9
|
|
|
|
|
10
|
|
|
namespace AppUtils\ImageHelper; |
|
11
|
|
|
|
|
12
|
|
|
use AppUtils\ImageHelper; |
|
13
|
|
|
use AppUtils\ImageHelper_Exception; |
|
14
|
|
|
use AppUtils\RGBAColor; |
|
15
|
|
|
use AppUtils\RGBAColor\ColorFactory; |
|
16
|
|
|
use GdImage; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Specialized class used for trimming images. |
|
20
|
|
|
* |
|
21
|
|
|
* @package Application Utils |
|
22
|
|
|
* @subpackage ImageHelper |
|
23
|
|
|
* @author Sebastian Mordziol <[email protected]> |
|
24
|
|
|
*/ |
|
25
|
|
|
class ImageTrimmer |
|
26
|
|
|
{ |
|
27
|
|
|
/** |
|
28
|
|
|
* @var resource|GdImage |
|
29
|
|
|
*/ |
|
30
|
|
|
private $sourceImage; |
|
31
|
|
|
private RGBAColor $trimColor; |
|
32
|
|
|
private ImageHelper $helper; |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param ImageHelper $helper |
|
36
|
|
|
* @param resource|GdImage $sourceImage |
|
37
|
|
|
* @param RGBAColor|null $trimColor |
|
38
|
|
|
* @throws ImageHelper_Exception |
|
39
|
|
|
*/ |
|
40
|
|
|
public function __construct(ImageHelper $helper, $sourceImage, ?RGBAColor $trimColor=null) |
|
41
|
|
|
{ |
|
42
|
|
|
ImageHelper::requireResource($sourceImage); |
|
43
|
|
|
|
|
44
|
|
|
$this->helper = $helper; |
|
45
|
|
|
$this->sourceImage = $sourceImage; |
|
46
|
|
|
$this->trimColor = $this->detectTrimColor($trimColor); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
private function detectTrimColor(?RGBAColor $trimColor) : RGBAColor |
|
50
|
|
|
{ |
|
51
|
|
|
$targetColor = ColorFactory::createAuto($trimColor); |
|
52
|
|
|
|
|
53
|
|
|
if($targetColor !== null) |
|
54
|
|
|
{ |
|
55
|
|
|
return $targetColor; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return $this->helper->getIndexedColors( |
|
59
|
|
|
$this->sourceImage, |
|
|
|
|
|
|
60
|
|
|
(int)imagecolorat($this->sourceImage, 0, 0) |
|
61
|
|
|
); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @return resource|GdImage|null |
|
66
|
|
|
*/ |
|
67
|
|
|
public function trim() |
|
68
|
|
|
{ |
|
69
|
|
|
$img = imagecropauto( |
|
70
|
|
|
$this->sourceImage, |
|
71
|
|
|
IMG_CROP_THRESHOLD, |
|
72
|
|
|
0.1, // Does not work at all with 0.0 |
|
73
|
|
|
imagecolorclosestalpha( |
|
74
|
|
|
$this->sourceImage, |
|
75
|
|
|
$this->trimColor->getRed()->get8Bit(), |
|
76
|
|
|
$this->trimColor->getGreen()->get8Bit(), |
|
77
|
|
|
$this->trimColor->getBlue()->get8Bit(), |
|
78
|
|
|
$this->trimColor->getAlpha()->get7Bit() |
|
79
|
|
|
) |
|
80
|
|
|
); |
|
81
|
|
|
|
|
82
|
|
|
if($img !== false) { |
|
83
|
|
|
return $img; |
|
|
|
|
|
|
84
|
|
|
} |
|
85
|
|
|
|
|
86
|
|
|
return null; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|