@@ -25,6 +25,7 @@ class ColorProcessor implements ColorProcessorInterface
25
25
*/
26
26
public function __construct (protected ColorspaceInterface $ colorspace = new Colorspace ())
27
27
{
28
+ //
28
29
}
29
30
30
31
/**
@@ -57,14 +58,29 @@ public function colorToNative(ColorInterface $color): int
57
58
*/
58
59
public function nativeToColor (mixed $ value ): ColorInterface
59
60
{
60
- if (!is_int ($ value )) {
61
- throw new ColorException ('GD driver can only decode colors in integer format. ' );
61
+ if (!is_int ($ value ) && ! is_array ( $ value ) ) {
62
+ throw new ColorException ('GD driver can only decode colors in integer and array format. ' );
62
63
}
63
64
64
- $ a = ($ value >> 24 ) & 0xFF ;
65
- $ r = ($ value >> 16 ) & 0xFF ;
66
- $ g = ($ value >> 8 ) & 0xFF ;
67
- $ b = $ value & 0xFF ;
65
+ if (is_array ($ value )) {
66
+ // array conversion
67
+ if (!$ this ->isValidArrayColor ($ value )) {
68
+ throw new ColorException (
69
+ 'GD driver can only decode array color format array{red: int, green: int, blue: int, alpha: int}. ' ,
70
+ );
71
+ }
72
+
73
+ $ r = $ value ['red ' ];
74
+ $ g = $ value ['green ' ];
75
+ $ b = $ value ['blue ' ];
76
+ $ a = $ value ['alpha ' ];
77
+ } else {
78
+ // integer conversion
79
+ $ a = ($ value >> 24 ) & 0xFF ;
80
+ $ r = ($ value >> 16 ) & 0xFF ;
81
+ $ g = ($ value >> 8 ) & 0xFF ;
82
+ $ b = $ value & 0xFF ;
83
+ }
68
84
69
85
// convert gd apha integer to intervention alpha integer
70
86
// ([opaque]0-127[transparent]) to ([opaque]255-0[transparent])
@@ -93,4 +109,49 @@ protected function convertRange(
93
109
): float |int {
94
110
return ceil (((($ input - $ min ) * ($ targetMax - $ targetMin )) / ($ max - $ min )) + $ targetMin );
95
111
}
112
+
113
+ /**
114
+ * Check if given array is valid color format
115
+ * array{red: int, green: int, blue: int, alpha: int}
116
+ * i.e. result of imagecolorsforindex()
117
+ *
118
+ * @param array<mixed> $color
119
+ * @return bool
120
+ */
121
+ private function isValidArrayColor (array $ color ): bool
122
+ {
123
+ if (!array_key_exists ('red ' , $ color )) {
124
+ return false ;
125
+ }
126
+
127
+ if (!array_key_exists ('green ' , $ color )) {
128
+ return false ;
129
+ }
130
+
131
+ if (!array_key_exists ('blue ' , $ color )) {
132
+ return false ;
133
+ }
134
+
135
+ if (!array_key_exists ('alpha ' , $ color )) {
136
+ return false ;
137
+ }
138
+
139
+ if (!is_int ($ color ['red ' ])) {
140
+ return false ;
141
+ }
142
+
143
+ if (!is_int ($ color ['green ' ])) {
144
+ return false ;
145
+ }
146
+
147
+ if (!is_int ($ color ['blue ' ])) {
148
+ return false ;
149
+ }
150
+
151
+ if (!is_int ($ color ['alpha ' ])) {
152
+ return false ;
153
+ }
154
+
155
+ return true ;
156
+ }
96
157
}
0 commit comments