从这个SO答案复制,作者为Cullub。
这段代码完美地将用户电子邮件转换为用户头像颜色。经过长时间的搜索,我得到了正确的十六进制值,类似于在前端使用JavaScript生成的值。
简而言之:完整的代码可以在Pastebin上找到。
function stringToColor($string)
{
$hash = 0;
$l = 70;
$s = 60;
for ($i = 0; $i < strlen($string); $i++) {
$hash = ord($string[$i]) + (($hash << 5) - $hash);
}
$h = fmod($hash, 360);
return $this->hslToHex($h, $s, $l, true);
}
function hslToHex($h, $s, $l, $prependPound = true)
{
$rgb = $this->hslToRgb($h, $s, $l);
$hexR = $rgb['r'];
$hexG = $rgb['g'];
$hexB = $rgb['b'];
$hexR = round($hexR);
$hexG = round($hexG);
$hexB = round($hexB);
$hexR = dechex($hexR);
$hexG = dechex($hexG);
$hexB = dechex($hexB);
if (strlen($hexR) != 2) {
if (strlen($hexR) == 1) {
$hexR = "0" . $hexR;
} else {
return false;
}
}
if (strlen($hexG) != 2) {
if (strlen($hexG) == 1) {
$hexG = "0" . $hexG;
} else {
return false;
}
}
if (strlen($hexB) != 2) {
if (strlen($hexB) == 1) {
$hexB = "0" . $hexB;
} else {
return false;
}
}
$hex = "";
if ($prependPound) {
$hex = "#";
}
$hex = $hex . $hexR . $hexG . $hexB;
return $hex;
}
function hslToRgb($h, $s, $l)
{
$h /= 360;
$s /= 100;
$l /= 100;
if ($s == 0) {
$r = $l * 255;
$g = $l * 255;
$b = $l * 255;
} else {
if ($l < 0.5) {
$temp2 = $l * (1 + $s);
} else {
$temp2 = ($l + $s) - ($s * $l);
}
$temp1 = 2 * $l - $temp2;
$r = 255 * $this->hueToRgb($temp1, $temp2, $h + (1 / 3));
$g = 255 * $this->hueToRgb($temp1, $temp2, $h);
$b = 255 * $this->hueToRgb($temp1, $temp2, $h - (1 / 3));
}
$rgb['r'] = $r;
$rgb['g'] = $g;
$rgb['b'] = $b;
return $rgb;
}
function hueToRgb($temp1, $temp2, $hue)
{
if ($hue < 0) {
$hue += 1;
}
if ($hue > 1) {
$hue -= 1;
}
if ((6 * $hue) < 1) {
return ($temp1 + ($temp2 - $temp1) * 6 * $hue);
} elseif ((2 * $hue) < 1) {
return $temp2;
} elseif ((3 * $hue) < 2) {
return ($temp1 + ($temp2 - $temp1) * ((2 / 3) - $hue) * 6);
}
return $temp1;
}
array(3) { ["r"]=> float(76.5) ["g"]=> float(155.55) ["b"]=> float(229.5) }
。使用printf的格式说明符,你可以输出十进制数。printf("rgb = %d,%d,%d<br>", $result['r'], $result['g'], $result['b']);
- enhzflep