hex to rgba php

Solutions on MaxInterview for hex to rgba php by the best coders in the world

showing results for - "hex to rgba php"
Niko
14 Mar 2018
1function hex2rgba($color, $opacity = false) {
2 
3	$default = 'rgb(0,0,0)';
4 
5	//Return default if no color provided
6	if(empty($color))
7          return $default; 
8 
9	//Sanitize $color if "#" is provided 
10        if ($color[0] == '#' ) {
11        	$color = substr( $color, 1 );
12        }
13 
14        //Check if color has 6 or 3 characters and get values
15        if (strlen($color) == 6) {
16                $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
17        } elseif ( strlen( $color ) == 3 ) {
18                $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
19        } else {
20                return $default;
21        }
22 
23        //Convert hexadec to rgb
24        $rgb =  array_map('hexdec', $hex);
25 
26        //Check if opacity is set(rgba or rgb)
27        if($opacity){
28        	if(abs($opacity) > 1)
29        		$opacity = 1.0;
30        	$output = 'rgba('.implode(",",$rgb).','.$opacity.')';
31        } else {
32        	$output = 'rgb('.implode(",",$rgb).')';
33        }
34 
35        //Return rgb(a) color string
36        return $output;
37}