如何将字符串转换为html颜色代码哈希?

use*_*562 17 html php hash colors

我想将字符串表示为任意的html颜色.

例:

"等等等等"=#FFCC00
"foo foo 2"=#565656

实际的颜色代码是什么并不重要,只要它是有效的十六进制HTML颜色代码并且整个光谱都能很好地表示.

我想第一步是在字符串上做一个MD5,然后以某种方式将其转换为十六进制颜色代码?

更新:用法示例是在服务器上生成文件请求的可视报告.颜色不一定非常漂亮,人类的大脑更容易检测到数据中的模式等.

use*_*562 35

感谢指点,这似乎做了一个称职的工作:

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>';
Run Code Online (Sandbox Code Playgroud)

  • 正是我正在寻找的解决方案。 (3认同)
  • 这里提供了类似的概念但不同的哈希值:http://stackoverflow.com/questions/15704220/change-random-strings-into-colours-consistently 对我来说,它似乎提供了更多样化的颜色组合。也许 md5() 与 dechex(crc32()) 的哈希分布不同 (2认同)

sje*_*397 21

几乎总是,只使用随机颜色

  1. 看起来不太好
  2. 与背景发生冲突

我建议创建一个(长的)颜色列表,它们可以很好地与你的背景一起工作 - 然后用你的颜色数量散列字符串和模数(%)来得到表格的索引.

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];
}
Run Code Online (Sandbox Code Playgroud)


Rei*_*ien 17

我同意上面的sje397,完全随意的颜色可能最终看起来很讨厌.我建议选择恒定的饱和度+发光值,并根据内容改变色调,而不是制作一长串漂亮的颜色.要从HSL颜色获取RGB颜色,您可以使用类似于http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB中描述的颜色.

这是一个例子(在http://codepad.viper-7.com中尝试一些有用的东西,例如https://codepad.remoteinterview.io/ZXBMZWYJFO):

<?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);
}
?>
Run Code Online (Sandbox Code Playgroud)

  • 使用代码段,这将是最佳答案 (5认同)

ale*_*emb 6

一个班轮:

substr(md5($string), 0, 6);
Run Code Online (Sandbox Code Playgroud)