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