如何将RGBA颜色代码转换为PHP中的8位十六进制?
我正在尝试转换一些 rgba 值值适用于适合变电站alpha字幕文件。 .ass
文件格式需要一种颜色格式,例如& h12345690
,其中十六进制字节为蓝色,绿色,红色,alpha顺序。
我发现将8位十六进制颜色转换为RGBA的示例,但不相反。这是我基于一个答案之一组合的函数,但是alpha频道始终返回为零:
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;
}
但是,如果我使用rgba(123,223,215,.9)
进行测试,则会产生&amp; H7BDFD70
只有7个字符而不是8个字符。
此外,Alpha Channel(.9)始终达到零,因此似乎无法正常工作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
printf()
函数系列来转换为正确填充的十六进制字符串。小数不能在十六进制中表示,因此该值被视为0xff的分数。输出:
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.Output:
您可以使用DeChex()函数将RGBA颜色的每个参数转换为2个十六进制数字。
因此,在您的示例中,您必须加入RGBA的每个部分才能获得您的颜色的十六进制值:
dechex(123).Dechex(100).Dechex(23).Dechex(0.5*256)
注意:最后一个值不能以这种方式使用。为了获得结果不透明度(保持0到1)等于十六进制至255,并且必须将其乘以256。
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*256)
Notice: The last value can't be used that way. To get a result Opacity (which holds 0 to 1) equals Hex 0 to 255 and thatfor has to be multiplied by 256.