1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Artack\Color\Converter; |
6
|
|
|
|
7
|
|
|
use Artack\Color\Color\Color; |
8
|
|
|
use Artack\Color\Color\HSV; |
9
|
|
|
use Artack\Color\Color\RGB; |
10
|
|
|
use Webmozart\Assert\Assert; |
11
|
|
|
|
12
|
|
|
class RGBToHSVConverter implements ConverterInterface |
13
|
|
|
{ |
14
|
132 |
|
public function convert(Color $color): Color |
15
|
|
|
{ |
16
|
|
|
/* @var RGB $color */ |
17
|
132 |
|
Assert::isInstanceOf($color, RGB::class, sprintf('color should be an instance of [%s]', RGB::class)); |
18
|
|
|
|
19
|
131 |
|
$red = $color->getRed() / 255; |
20
|
131 |
|
$green = $color->getGreen() / 255; |
21
|
131 |
|
$blue = $color->getBlue() / 255; |
22
|
|
|
|
23
|
131 |
|
$cMax = max($red, $green, $blue); |
24
|
131 |
|
$cMin = min($red, $green, $blue); |
25
|
131 |
|
$cDelta = $cMax - $cMin; |
26
|
|
|
|
27
|
131 |
|
$hue = $cMax; |
28
|
|
|
|
29
|
131 |
|
if (0 == $cDelta) { |
30
|
11 |
|
$hue = 0; |
31
|
120 |
|
} elseif ($cMax === $red) { |
32
|
52 |
|
$hue = ($green - $blue) / $cDelta; |
33
|
68 |
|
} elseif ($cMax === $green) { |
34
|
40 |
|
$hue = ($blue - $red) / $cDelta + 2; |
35
|
28 |
|
} elseif ($cMax === $blue) { |
36
|
28 |
|
$hue = ($red - $green) / $cDelta + 4; |
37
|
|
|
} |
38
|
|
|
|
39
|
131 |
|
$hue = (int) round($hue * 60); |
40
|
131 |
|
$hue = $hue < 0 ? $hue + 360 : $hue; |
41
|
131 |
|
$saturation = 0 === $cMax ? 0 : $cDelta / $cMax; |
42
|
|
|
|
43
|
131 |
|
$saturation = $saturation > 1 || $saturation < 0 ? 1 : $saturation; |
44
|
131 |
|
$cMax = $cMax > 1 || $cMax < 0 ? 1 : $cMax; |
45
|
|
|
|
46
|
131 |
|
return new HSV($hue, $saturation * 100, $cMax * 100); |
47
|
|
|
} |
48
|
|
|
|
49
|
924 |
|
public static function supportsFrom(): string |
50
|
|
|
{ |
51
|
924 |
|
return RGB::class; |
52
|
|
|
} |
53
|
|
|
|
54
|
924 |
|
public static function supportsTo(): string |
55
|
|
|
{ |
56
|
924 |
|
return HSV::class; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|