@@ -343,19 +343,25 @@ public static function convertToColor(string $hex): ?string
343
343
}
344
344
345
345
/**
346
- * Parse a hex color into it's three RGB values.
346
+ * Parse a hex color into it's four RGBA values.
347
347
*
348
- * @return array{int, int, int}
348
+ * @return array{int, int, int, int }
349
349
*/
350
350
public static function parseHexColor (string $ hex ): array
351
351
{
352
+ $ tmp = substr ($ hex , 1 );
353
+ if (strlen ($ tmp ) % 3 == 0 ) {
354
+ $ mult = strlen ($ tmp ) / 3 ;
355
+ $ hex += 'f ' * $ mult ;
356
+ }
352
357
// Source: https://stackoverflow.com/a/21966100
353
358
$ length = (strlen ($ hex ) - 1 ) / 3 ;
354
359
$ fact = [17 , 1 , 0.062272 ][$ length - 1 ];
355
360
return [
356
361
(int )round (hexdec (substr ($ hex , 1 , $ length )) * $ fact ),
357
362
(int )round (hexdec (substr ($ hex , 1 + $ length , $ length )) * $ fact ),
358
363
(int )round (hexdec (substr ($ hex , 1 + 2 * $ length , $ length )) * $ fact )
364
+ (int)round (hexdec (substr ($ hex , 1 + 3 * $ length , $ length )) * $ fact )
359
365
];
360
366
}
361
367
@@ -371,21 +377,47 @@ public static function componentToHex(int $component): string
371
377
/**
372
378
* Convert an RGB triple into a CSS hex color.
373
379
*
374
- * @param array{int, int, int} $color
380
+ * @param array{int, int, int}|array{int, int, int, int} $color
375
381
*/
376
382
public static function rgbToHex (array $ color ): string
377
383
{
378
384
$ result = "# " ;
385
+ if (count ($ color ) === 3 ) {
386
+ $ color [] = 255 ;
387
+ } elseif (count ($ color ) !== 4 ) {
388
+ throw Exception ("Invalid RGB number. " );
389
+ }
379
390
for (int $ i =0 ; $ i <count ($ color ); $ i ++) {
380
391
$ result += static ::componentToHex ($ color [$ i ]);
381
392
}
382
393
return $ result ;
383
394
}
384
395
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
386
417
{
387
418
// 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 );
389
421
390
422
[$ lr , $ lg , $ lb ] = [
391
423
pow ($ r / 255 , 2.4 ),
0 commit comments