1
|
|
|
<?php namespace Arcanedev\Color\Converters; |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Trait HEXTrait |
5
|
|
|
* |
6
|
|
|
* @package Arcanedev\Color\Converters |
7
|
|
|
* @author ARCANEDEV <[email protected]> |
8
|
|
|
*/ |
9
|
|
|
trait HEXTrait |
10
|
|
|
{ |
11
|
|
|
/* ------------------------------------------------------------------------------------------------ |
12
|
|
|
| Main Functions |
13
|
|
|
| ------------------------------------------------------------------------------------------------ |
14
|
|
|
*/ |
15
|
|
|
/** |
16
|
|
|
* Convert a HEX color to an RGB array (alias). |
17
|
|
|
* |
18
|
|
|
* @see fromHexToRgb |
19
|
|
|
* |
20
|
|
|
* @param string $hex |
21
|
|
|
* |
22
|
|
|
* @return array |
23
|
|
|
*/ |
24
|
|
|
public static function hexToRgb($hex) |
25
|
|
|
{ |
26
|
|
|
return (new self)->fromHexToRgb($hex); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Convert a HEX color to an RGB array. |
31
|
|
|
* |
32
|
|
|
* @param string $hex |
33
|
|
|
* |
34
|
|
|
* @return array |
35
|
|
|
*/ |
36
|
|
|
public function fromHexToRgb($hex) |
37
|
|
|
{ |
38
|
|
|
$value = str_replace('#', '', $hex); |
39
|
|
|
|
40
|
|
|
return array_map('hexdec', strlen($value) === 6 ? [ |
41
|
|
|
substr($value, 0, 2), // RED |
42
|
|
|
substr($value, 2, 2), // GREEN |
43
|
|
|
substr($value, 4, 2), // BLUE |
44
|
|
|
] : [ |
45
|
|
|
str_repeat(substr($value, 0, 1), 2), // RED |
46
|
|
|
str_repeat(substr($value, 1, 1), 2), // GREEN |
47
|
|
|
str_repeat(substr($value, 2, 1), 2), // BLUE |
48
|
|
|
]); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Convert RGB values to a HEX color (alias). |
53
|
|
|
* |
54
|
|
|
* @see fromRgbToHex |
55
|
|
|
* |
56
|
|
|
* @param int $red |
57
|
|
|
* @param int $green |
58
|
|
|
* @param int $blue |
59
|
|
|
* |
60
|
|
|
* @return string |
61
|
|
|
*/ |
62
|
|
|
public static function rgbToHex($red, $green, $blue) |
63
|
|
|
{ |
64
|
|
|
return (new self)->fromRgbToHex($red, $green, $blue); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Convert RGB values to a HEX color. |
69
|
|
|
* |
70
|
|
|
* @param int $red |
71
|
|
|
* @param int $green |
72
|
|
|
* @param int $blue |
73
|
|
|
* |
74
|
|
|
* @return string |
75
|
|
|
*/ |
76
|
|
|
public function fromRgbToHex($red, $green, $blue) |
77
|
|
|
{ |
78
|
|
|
return '#' . implode('', array_map(function ($value) { |
79
|
|
|
return str_pad(dechex($value), 2, '0', STR_PAD_LEFT); |
80
|
|
|
}, [$red, $green, $blue])); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|