Skip to content

Instantly share code, notes, and snippets.

@guimadaleno
Created September 1, 2022 15:21
Show Gist options
  • Save guimadaleno/81a7f62f588e22a0e8fb4d302b7f27ac to your computer and use it in GitHub Desktop.
Save guimadaleno/81a7f62f588e22a0e8fb4d302b7f27ac to your computer and use it in GitHub Desktop.
Convert HEX color to RGB(A)
<?php
/**
* Converts HEX color code to RGB(A)
* @param string $color
* @param int $opacity
* @return string
*/
function hex2rgba ($color, $opacity = false)
{
$default = 'rgb(0,0,0)';
if (empty($color))
return $default;
if ($color[0] == '#')
$color = substr($color, 1);
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;
$rgb = array_map('hexdec', $hex);
if (!$opacity)
return 'rgb('.implode(",",$rgb).')';
if (abs($opacity) > 1)
$opacity = 1.0;
return 'rgba('.implode(",",$rgb).','.$opacity.')';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment