在PHP中将RGB转换为十六进制颜色值


Convert RGB to hex color values in PHP

在我的代码中,我有

$color = rgb(255, 255, 255);

我想把它转换成十六进制颜色代码。像一样输出

$color = '#ffffff';

您可以使用以下函数

function fromRGB($R, $G, $B)
{
    $R = dechex($R);
    if (strlen($R)<2)
    $R = '0'.$R;
    $G = dechex($G);
    if (strlen($G)<2)
    $G = '0'.$G;
    $B = dechex($B);
    if (strlen($B)<2)
    $B = '0'.$B;
    return '#' . $R . $G . $B;
}

然后,echo fromRGB(115,25,190);将打印#7319be

来源:RGB到十六进制颜色和十六进制颜色到RGB-PHP

您可以尝试下面这段简单的代码。您也可以在代码中动态传递rgb代码。

$rgb = (123,222,132);
$rgbarr = explode(",",$rgb,3);
echo sprintf("#%02x%02x%02x", $rgbarr[0], $rgbarr[1], $rgbarr[2]);

这将返回类似#7bde84

的代码

这里有一个函数,它将接受rgbrgba的字符串版本,并返回hex颜色。

    function rgb_to_hex( string $rgba ) : string {
        if ( strpos( $rgba, '#' ) === 0 ) {
            return $rgba;
        }
        preg_match( '/^rgba?['s+]?'(['s+]?('d+)['s+]?,['s+]?('d+)['s+]?,['s+]?('d+)['s+]?/i', $rgba, $by_color );
        return sprintf( '#%02x%02x%02x', $by_color[1], $by_color[2], $by_color[3] );
    }

示例:rgb_to_hex( 'rgba(203, 86, 153, 0.8)' );//返回#cb5699

你可以试试这个

function rgb2html($r, $g=-1, $b=-1)
{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;
    $r = intval($r); $g = intval($g);
    $b = intval($b);
    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));
    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}

如果你想使用外部解决方案,spatie有一个包可以做你想做的事情:

https://github.com/spatie/color

$rgb = Rgb::fromString('rgb(55,155,255)');
echo $rgb->red(); // 55
echo $rgb->green(); // 155
echo $rgb->blue(); // 255
echo $rgb; // rgb(55,155,255)
$rgba = $rgb->toRgba(); // `Spatie'Color'Rgba`
$rgba->alpha(); // 1
echo $rgba; // rgba(55,155,255,1)
$hex = $rgb->toHex(); // `Spatie'Color'Hex`
echo $hex; // #379bff
$hsl = $rgb->toHsl();
echo $hsl; // hsl(210,100%,100%)

基于Mat Lipe的函数,这将更改字符串中rgb颜色的所有实例:

$html = preg_replace_callback("/rgba?'s*'('s*('d+)'s*,'s*('d+)'s*,'s*('d+)'s*,*'s*'d*'s*')/i", function($matches) {
    return strtoupper(sprintf("#%02x%02x%02x", $matches[1], $matches[2], $matches[3]));
}, $html);

如果您喜欢小写十六进制,可以删除strtoupper