我希望将字符串表示为任意的html颜色。
例如:
"blah blah" = #FFCC00
"foo foo 2" = #565656
实际的颜色代码并不重要,只要它是有效的十六进制HTML颜色代码,并且整个光谱被相对平均地表示即可。
我想第一步应该是对字符串进行MD5,然后以某种方式将其转换为十六进制颜色代码?
更新:使用示例是为了在服务器上生成文件请求的视觉报告。 颜色不必看起来漂亮,更多是为了人类大脑能够更容易地检测到数据中的模式等。
我希望将字符串表示为任意的html颜色。
例如:
"blah blah" = #FFCC00
"foo foo 2" = #565656
实际的颜色代码并不重要,只要它是有效的十六进制HTML颜色代码,并且整个光谱被相对平均地表示即可。
我想第一步应该是对字符串进行MD5,然后以某种方式将其转换为十六进制颜色代码?
更新:使用示例是为了在服务器上生成文件请求的视觉报告。 颜色不必看起来漂亮,更多是为了人类大脑能够更容易地检测到数据中的模式等。
谢谢你的指导,这个方法看起来做得很好:
function stringToColorCode($str) {
$code = dechex(crc32($str));
$code = substr($code, 0, 6);
return $code;
}
$str = 'test123';
print '<span style="background-color:#'.stringToColorCode($str).'">'.$str.'</span>';
通常情况下,仅使用随机颜色会:
我建议创建一个(较长的)颜色列表,这些颜色彼此之间和背景搭配得很好 - 然后只需对字符串进行哈希并取模(%)以获得索引表中的索引。
public function colorFromString($string)
{
$colors = [
'#0074D9',
'#7FDBFF',
'#39CCCC',
// this list should be as long as practical to avoid duplicates
];
// generate a partial hash of the string (a full hash is too long for the % operator)
$hash = substr(sha1($string), 0, 10);
// determine the color index
$colorIndex = hexdec($hash) % count($colors);
return $colors[$colorIndex];
}
<?php
function hsl2rgb($H, $S, $V) {
$H *= 6;
$h = intval($H);
$H -= $h;
$V *= 255;
$m = $V*(1 - $S);
$x = $V*(1 - $S*(1-$H));
$y = $V*(1 - $S*$H);
$a = [[$V, $x, $m], [$y, $V, $m],
[$m, $V, $x], [$m, $y, $V],
[$x, $m, $V], [$V, $m, $y]][$h];
return sprintf("#%02X%02X%02X", $a[0], $a[1], $a[2]);
}
function hue($tstr) {
return unpack('L', hash('adler32', $tstr, true))[1];
}
$phrase = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
$words = [];
foreach (explode(' ', $phrase) as $word)
$words[hue($word)] = $word;
ksort($words);
foreach ($words as $h => $word) {
$col = hsl2rgb($h/0xFFFFFFFF, 0.4, 1);
printf('<span style="color:%s">%s</span> ', $col, $word);
}
?>
sha1()
哈希$tstr
,我确实会得到更多的颜色,但其中一些仍然看起来像重复的。是否有更好的方法将任意文本转换为色调,或者对于我的约20个值,我要求太多了? - ᴍᴇʜᴏᴠ一个简短的句子:
substr(md5($string), 0, 6);