Search code examples
phprgba

PHP Opacity multiplication


So I have a string like this "rgba(66, 66, 66, 1)" how could I multiply the last digit or number of it by 255. It would also need to be compliant with rgba(214, 234, 216, 0.6) for example. I wasnt sure how to do this as the rgb aspect and the opacity could be different every time.


Solution

  • Here is a working function that parses the rgba format and returns an array with each color, along with scaling a float alpha value out to 0-255. It also clamps all the values between 0-255 to prevent overflows outside that range. If an invalid rgb string is passed in, the function returns false.

    Function (demo):

    /**
     * Parses an RGBA string and returns and array with each color
     * @param  string $str The RGBA string, ex: "rgba(66, 66, 66, 1)"
     * @return array       Returns an array with each r, g, b and a value or false if an invalid string is passed in.
     */
    function parseRGBA($str){
        //match the rgba string and get it's part
        if(preg_match('/rgba\( *([\d\.-]+), *([\d\.-]+), *([\d\.-]+), *([\d\.-]+) *\)/i', $str, $m)){
            $out = array(
                'r'=>intval($m[1]), //get the red
                'g'=>intval($m[2]), //get the green
                'b'=>intval($m[3]), //get the blue
                'a'=>round(floatval($m[4]) * 255), //get the alpha and scale to 0-255
            );
    
            //clamp each  value between 0 and 255
            array_walk($out, function(&$v){ $v = min(255, max(0, $v)); });
    
            return $out;
        }
        return false;
    }
    

    Example:

    echo '<pre>';
    echo "Normal value: ";
    print_r(parseRGBA("rgba(66, 66, 66, 1)"));
    
    echo "Red > 255: ";
    print_r(parseRGBA("rgba(660, 66, 66, 1)"));
    
    echo "Green < 0: ";
    print_r(parseRGBA("rgba(66, -66, 66, 1)"));
    
    echo "Alpha float (normal): ";
    print_r(parseRGBA("rgba(66, 66, 66, 0.6)"));
    
    echo "Alpha overflow: ";
    print_r(parseRGBA("rgba(66, 66, 66, 10)"));
    

    outputs:

    Normal value: Array
    (
        [r] => 66
        [g] => 66
        [b] => 66
        [a] => 255
    )
    Red > 255: Array
    (
        [r] => 255
        [g] => 66
        [b] => 66
        [a] => 255
    )
    Green < 0: Array
    (
        [r] => 66
        [g] => 0
        [b] => 66
        [a] => 255
    )
    Alpha float (normal): Array
    (
        [r] => 66
        [g] => 66
        [b] => 66
        [a] => 153
    )
    Alpha overflow: Array
    (
        [r] => 66
        [g] => 66
        [b] => 66
        [a] => 255
    )