我正在尝试将一些 rgba 值转换为适合 SubStation 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)
测试它,它会产生 &H7bdfd70
,它只有 7 个字符而不是 8 个。
此外,Alpha 通道 (.9) 始终为零,因此这似乎无法正常工作。
您可以使用
printf()
系列函数转换为正确填充的十六进制字符串。小数无法用十六进制表示,因此该值取为 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;
输出:
&H17647B7F
您可以使用 dechex() 函数将 rgba 颜色的每个参数转换为 2 个十六进制数字。
因此,在您的示例中,您必须连接 rgba 的每个部分才能获取颜色的十六进制值:
dechex(123).dechex(100).dechex(23).dechex(0.5)