Convert hex color to RGB values in PHP

前端 未结 15 1859
轮回少年
轮回少年 2020-11-30 21:32

What would be a good way to convert hex color values like #ffffff into the single RGB values 255 255 255 using PHP?

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 22:32

    This is the only solution that worked for me. Some of the answers were not consistent enough.

        function hex2rgba($color, $opacity = false) {
    
            $default = 'rgb(0,0,0)';
    
            //Return default if no color provided
            if(empty($color))
                  return $default;
    
            //Sanitize $color if "#" is provided
                if ($color[0] == '#' ) {
                    $color = substr( $color, 1 );
                }
    
                //Check if color has 6 or 3 characters and get values
                if (strlen($color) == 6) {
                        $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
                } elseif ( strlen( $color ) == 3 ) {
                        $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
                } else {
                        return $default;
                }
    
                //Convert hexadec to rgb
                $rgb =  array_map('hexdec', $hex);
    
                //Check if opacity is set(rgba or rgb)
                if($opacity){
                    if(abs($opacity) > 1)
                        $opacity = 1.0;
                    $output = 'rgba('.implode(",",$rgb).','.$opacity.')';
                } else {
                    $output = 'rgb('.implode(",",$rgb).')';
                }
    
                //Return rgb(a) color string
                return $output;
        }
        //hex2rgba("#ffaa11",1)
    

提交回复
热议问题