1

I'm attempting to convert some rgba values into a format suitable for SubStation Alpha subtitle files. The .ass file format requires a colour format like &H12345690 where the hex bytes are in blue, green, red, alpha order.

I am finding examples converting 8 digit hex colors into RGBA, but not the other way around. Here is a function I put together based one of the answers, but the alpha channel is always returned as zero:

function rgbtohex($string) {
    $string = str_replace("rgba","",$string);
    $string = str_replace("rgb","",$string);
    $string = str_replace("(","",$string);
    $string = str_replace(")","",$string);
    $colorexplode = explode(",",$string);    
    $hex = '&H';
    
    foreach($colorexplode AS $c) {
        echo "C" . $c . " " . dechex($c) . "<br><br>";
        $hex .= dechex($c);      
    }
    return $hex;
}

But if I test it with rgba(123,223,215,.9) it produces &H7bdfd70 which only has 7 characters instead of 8.

Also, the alpha channel (.9) always comes out to zero, so that doesn't appear to be working correctly.

miken32
  • 42,008
  • 16
  • 111
  • 154
CRAIG
  • 977
  • 2
  • 11
  • 25

2 Answers2

6

You can use the printf() family of functions to convert to a properly padded hex string. Decimals cannot be represented in hex, so the value is taken as a fraction of 0xFF.

$rgba = "rgba(123,100,23,.5)";

// get the values
preg_match_all("/([\\d.]+)/", $rgba, $matches);

// output
$hex = sprintf(
    "&H%02X%02X%02X%02X",
    $matches[1][2], // blue
    $matches[1][1], // green
    $matches[1][0], // red
    $matches[1][3] * 255, // adjusted opacity
);
echo $hex;

Output:

&H17647B7F
miken32
  • 42,008
  • 16
  • 111
  • 154
  • Hey @miken32 apparently this format (used for aegisub .ass subtitle files) needs to be in BGR instead of RGB. Feel free to edit if you want. I didn't realize this when I posted it. Otherwise your function seems to work well. – CRAIG May 06 '22 at 13:20
-1

You can use the dechex() function to convert each param of your rgba color to a 2 hex digit.

So in your example you have to concat each part of the rgba to get the hex value of your color : dechex(123).dechex(100).dechex(23).dechex(0.5)

Guillaume
  • 319
  • 1
  • 11
  • I tried that and built a function to test, but isn't working. I added it to the question. Only produces 7 characters and the alpha channel is always zero. Thx! – CRAIG May 04 '22 at 18:30