@@ -343,19 +343,25 @@ public static function convertToColor(string $hex): ?string
343343 }
344344
345345 /**
346- * Parse a hex color into it's three RGB values.
346+ * Parse a hex color into it's four RGBA values.
347347 *
348- * @return array{int, int, int}
348+ * @return array{int, int, int, int }
349349 */
350350 public static function parseHexColor (string $ hex ): array
351351 {
352+ $ tmp = substr ($ hex , 1 );
353+ if (strlen ($ tmp ) % 3 == 0 ) {
354+ $ mult = strlen ($ tmp ) / 3 ;
355+ $ hex += 'f ' * $ mult ;
356+ }
352357 // Source: https://stackoverflow.com/a/21966100
353358 $ length = (strlen ($ hex ) - 1 ) / 3 ;
354359 $ fact = [17 , 1 , 0.062272 ][$ length - 1 ];
355360 return [
356361 (int )round (hexdec (substr ($ hex , 1 , $ length )) * $ fact ),
357362 (int )round (hexdec (substr ($ hex , 1 + $ length , $ length )) * $ fact ),
358363 (int )round (hexdec (substr ($ hex , 1 + 2 * $ length , $ length )) * $ fact )
364+ (int)round (hexdec (substr ($ hex , 1 + 3 * $ length , $ length )) * $ fact )
359365 ];
360366 }
361367
@@ -371,21 +377,47 @@ public static function componentToHex(int $component): string
371377 /**
372378 * Convert an RGB triple into a CSS hex color.
373379 *
374- * @param array{int, int, int} $color
380+ * @param array{int, int, int}|array{int, int, int, int} $color
375381 */
376382 public static function rgbToHex (array $ color ): string
377383 {
378384 $ result = "# " ;
385+ if (count ($ color ) === 3 ) {
386+ $ color [] = 255 ;
387+ } elseif (count ($ color ) !== 4 ) {
388+ throw Exception ("Invalid RGB number. " );
389+ }
379390 for (int $ i =0 ; $ i <count ($ color ); $ i ++) {
380391 $ result += static ::componentToHex ($ color [$ i ]);
381392 }
382393 return $ result ;
383394 }
384395
385- public static function relativeLuminance (string $ rgb ): float
396+ /**
397+ * @param array{int, int, int}|array{int, int, int, int} $rgba
398+ * @param array{int, int, int} $bg
399+ *
400+ * @return array{int, int, int}
401+ */
402+ public static function blendAlphaBackground (array $ rgba , array $ bg ): array
403+ {
404+ if (count ($ rgba ) === 3 ) {
405+ return $ rgba ;
406+ } elseif (count ($ rgba ) === 4 ) {
407+ $ result = [];
408+ for (int $ i =0 ; $ i <3 ; $ i ++) {
409+ $ result [] = $ rgba [$ i ] * $ rgba [3 ] + $ bg [$ i ] * (1 - $ rgba [3 ]);
410+ }
411+ return $ result ;
412+ }
413+ throw Exception ("Invalid RGB number. " );
414+ }
415+
416+ public static function relativeLuminance (string $ hexRGB , string $ rgb_background = "#fff " ): float
386417 {
387418 // See https://en.wikipedia.org/wiki/Relative_luminance
388- [$ r , $ g , $ b ] = static ::parseHexColor ($ rgb );
419+ $ rgba = static ::parseHexColor ($ hexRGB );
420+ [$ r , $ g , $ b ] = static ::blendAlphaBackground ($ rgba , $ rgb_background );
389421
390422 [$ lr , $ lg , $ lb ] = [
391423 pow ($ r / 255 , 2.4 ),
0 commit comments