January 4, 2016

HEX to RGBA color converter in PHP

In a project I needed color codes which were inserted in hex code and i needed to make different shades of this color so I needed a HEX to RGBA converter in PHP.

This below code highly satisfied my needs and I am sharing this with you guys.

It needed first variable as a HEX input and second as opacity.

 

/***************************************************************************
Hex to rgba converter
***************************************************************************/

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;
}

 

You may also like...

Leave a Reply