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