我有转换三个HEX颜色代码的工具,为RGB颜色代码。
到目前为止,我对HEX到RGB的了解是:
if(strlen($hex) == 3) {
$color['r'] = hexdec(substr($hex, 0, 1) . $r);
$color['g'] = hexdec(substr($hex, 1, 1) . $g);
$color['b'] = hexdec(substr($hex, 2, 1) . $b);
}
当我把RGB代码转换回HEX时,它就不同了。
例如:#FFF becomes 15, 15, 15
但15, 15, 15 is #0F0F0F
我也不确定是否将RGB转换回三重HEX代码。我的RGB到HEX的代码如下:
$hex = str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
非常感谢您的帮助!提前感谢!
看起来您需要以不同的方式处理三元组:#XYZ=#XXYYZZ#例如,FFF应该与#FFFFFF相同,或者,(255255255),而不是(15,15,15)。
因此,一种方法是使用以下代码:
if(strlen($hex) == 3) {
$color['r'] = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
$color['g'] = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
$color['b'] = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
}
注意,我不包括$r、$g和$b,因为我不知道你为什么要使用它们。
function hex2rgb($hex)
{
// Ensure we're working only with upper-case hex values,
// toss out any extra characters.
$hex = preg_replace('/[^A-F0-9]/', '', strtoupper($hex));
// Convert 3-letter hex RGB codes into 6-letter hex RGB codes
$hex_len = strlen($hex);
if ($hex_len == 3) {
$new_hex = '';
for ($i = 0; $i < $hex_len; ++$i) {
$new_hex .= $hex[$i].$hex[$i];
}
$hex = $new_hex;
}
// Calculate the RGB values
$rgb['r'] = hexdec(substr($hex, 0, 2));
$rgb['g'] = hexdec(substr($hex, 2, 2));
$rgb['b'] = hexdec(substr($hex, 4, 2));
return $rgb;
}
print_r(hex2rgb('#fff')); // r: 255 g: 255 b: 255
print_r(hex2rgb('#AE9C00')); // r: 174 g: 156 b: 0