Search code examples
phpcolorsrgbaargb

PHP convert ARGB to RGBA?


Need solution or description of: How to convert color value from ARGB to RGBA which is possible to use for css:

Examples:

ARGB color : #ff502797 convert to RGBA
RGBA result example: rgba(80,39,151,1)

thx.


Solution

  • ARGB contains 4 groups of HEX values(channels): Alpha, Red, Green, Blue.

    Scheme: Exampe: #ff502797 - color in ARGB formatt Elements on positions:

    0,1 - Alpa  (ff)
    2,3 - Red   (50)
    4,5 - Green (27)
    6,7 - Blue  (97)
    

    After this convert each channel to decimal. And putt on their places into RBGA: rgba(Red,Green,Blue,Alpha) - rgba(80,39,151,1)

    Example function:

    function argb2rgba($color)
        {
            $output = 'rgba(0,0,0,1)';
    
            if (empty($color))
                return $output;
    
            if ($color[0] == '#') {
                $color = substr($color, 1);
            }
    
            if (strlen($color) == 8) { //ARGB
                $opacity = round(hexdec($color[0].$color[1]) / 255, 2);
                $hex = array($color[2].$color[3], $color[4].$color[5], $color[6].$color[7]);
                $rgb = array_map('hexdec', $hex);
                $output = 'rgba(' . implode(",", $rgb) . ',' . $opacity . ')';
            }
    
            return $output;
        }