Answer the question
In order to leave comments, you need to log in
How to get RGBA colors from HEX?
Hello. Converting from HEX to RGB is not a problem, but how to do it in RGBA, that is, taking into account transparency?
Answer the question
In order to leave comments, you need to log in
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;
}
As far as I know HEX = RGB but not RGBA.
For example: the color cornsilk is #FFF8DC, if you disassemble it in parts, then FF(255) F8(248) DC(220), as you can see, there is no additional character for the alpha channel, so the best option is to use the code that above in the answers.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question