如何在PHP中将RGBA转换为HEX6颜色代码?

问题描述 投票:0回答:2

我想在 PHP 中将 RGBA 值转换为十六进制。我找到了 RGB 到十六进制的很好的帮助(例如 在 PHP 中将 RGB 转换为十六进制颜色值)。现在我也尝试更改 A 值(例如 rgba(80,80,80,0.5) 更改为#D3D3D3(6 位数字))。当然,假设背景是白色。

低于尝试。 有人对我如何做得更好有任何建议吗? 如何获得匹配颜色但更浅的颜色?

public static function convertRGBAtoHEX6(string $rgba): string
{

    if ( strpos( $rgba, '#' ) === 0 ) {
        return $rgba;
    }

    preg_match( '/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i', $rgba, $by_color );
    
    if(isset($by_color[4])) 
    {
        $by_color[4] = 2 - $by_color[4];

        $by_color[1] = $by_color[1] * $by_color[4];
        $by_color[2] = $by_color[2] * $by_color[4];
        $by_color[3] = $by_color[3] * $by_color[4];
    }

    return sprintf( '#%02x%02x%02x', $by_color[1], $by_color[2], $by_color[3] );

}
php colors rgba
2个回答
0
投票

我想出了这个解决方案:

<?php

$rgba = 'rgba(80,80,80,0.5)';

function blendChannels(float $alpha, int $channel1, int $channel2): int
{
    // blend 2 channels
    return intval(($channel1 * $alpha) + ($channel2 * (1.0 - $alpha)));
}

function convertRGBAtoHEX6(string $rgba): string
{
    // sanitize
    $rgba = strtolower(trim($rgba));
    // check
    if (substr($rgba, 0, 5) != 'rgba(') {
        return $rgba;
    }
    // extract channels
    $channels = explode(',', substr($rgba, 5, strpos($rgba, ')') - 5));
    // compute rgb with white background
    $alpha = $channels[3];
    $r = blendChannels($alpha, $channels[0], 0xFF);
    $g = blendChannels($alpha, $channels[1], 0xFF);
    $b = blendChannels($alpha, $channels[2], 0xFF);
    return sprintf('#%02x%02x%02x', $r, $g, $b);
}

echo convertRGBAtoHEX6($rgba);

参见:https://3v4l.org/ick2o

结果是:

"#a7a7a7"

代码与您的代码基本相同,除了

blendChannels()
函数之外。该函数获取所提供的两个通道的所需数量。如果 alpha 为 1.0,则输出等于通道 1;如果 alpha 为 0.0,则输出等于通道 2;如果 alpha 为 0.5,则从两个通道获取相同的量。对所有 3 个通道执行此操作,您就完成了。


-1
投票

其实我不久前就完成了这个任务。

如果我们得到的颜色为

255,255,255,0.123

所以我们创建 reg 来检查
/(((25[0-5])|(2[0-4]\d)|(1?\d{0,2})|0), *){3}(0|(0\.\d{1,3})|1)$/

因此我们可以制作编码和解码功能

function encode(string $colorString)
{
    $colorArray = explode(',', $colorString);
    $colorArray[3] *= 255;
    $colorBytes = array_map(
        fn($part) =>  pack('C', (int)trim($part)),
        $colorArray
    );
    return implode($colorBytes);
}
function decode($hexColor)
{
    //$hexColor = stream_get_contents($hexColor); // If $hexColor is stream
    $colorArray = array_values(unpack('C*', $hexColor));
    return implode(
        ',',
        [$colorArray[0], $colorArray[1], $colorArray[2], round($colorArray[3]/255, 3)]
    );
}

我将我的颜色保存在数据库中。当我需要保存更多颜色时,我将其写入一个十六进制字符串,当我解码时,我将其分成 4 个字节的块

例如我有 ['255,123,125,1', '32,123,23,0.15']

foreach (['255,123,125,1', '32,123,23,0.15'] as $color) {
    $x = $this->encode($color);
    print('#' . strtoupper(bin2hex($x)) . "\n");
}

结果将:

#FF7B7DFF
#207B1726

试试这个,也许它会成为你的解决方案的目标

© www.soinside.com 2019 - 2024. All rights reserved.