DEV Community

Jacopo Valanzano
Jacopo Valanzano

Posted on • Edited on

PHP - Colour inversion

Since I couldn't find an algorithm to invert a color and get decent contrast (with PHP), I'm sharing my code.

The function below does not always pass WCAG (AA, AAA) tests!

function invertColor($hex) {

        $ihex = \dechex($hex);

        $r = \dechex(255 - \round(\hexdec(\substr($ihex, 0,2))));
        $g = \dechex(255 - \round(\hexdec(\substr($ihex, 2,2))));
        $b = \dechex(255 - \round(\hexdec(\substr($ihex, 4,2))));

        // If the color (rgb) has less than 2 characters, pad with zero
        $padZero = function ($str) {
            return \str_pad($str, 2, 0, \STR_PAD_LEFT);
        };

        // Pad with zero
        return $padZero($r) . $padZero($g) . $padZero($b);

    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)