将字符串转换为RGB颜色 [英] Hash string into RGB color

查看:1042
本文介绍了将字符串转换为RGB颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关如何将任意字符串散列为RGB颜色值的最佳做法吗?或更一般:到3个字节。

Is there a best practice on how to hash an arbitrary string into a RGB color value? Or to be more general: to 3 bytes.

你问:我什么时候需要这个?对我来说没关系,但想象任何GitHub上的管图网络页面。在那里你可以看到这样的:

You're asking: When will I ever need this? It doesn't matter to me, but imagine those tube graphs on any GitHub network page. There you can see something like this:

其中每个彩色线表示一个不同的git分支。对这些分支进行着色的低科技方法将是CLUT(颜色查找表)。更复杂的版本是:

Where every colored line means a distinct git branch. The low tech approach to color these branches would be a CLUT (color lookup table). The more sophisticated version would be:

$branchColor = hashStringToColor(concat($username,$branchname));

因为你每次看到分支表示时都需要一个静态颜色。对于奖励点:如何确保散列函数的均匀颜色分布?

Because you want a static color every time you see the branches representation. And for bonus points: How do you ensure an even color distribution of that hash function?

因此,我的问题的答案归结为 hashStringToColor()

So the answer to my question boils down to the implementation of hashStringToColor().

推荐答案

空间。这减少了如何将随机32位数转换为3字节RGB空间的问题。我看到没有什么错,只是采取低3字节。

A good hash function will provide a near uniform distribution over the key space. This reduces the question to how do I convert a random 32 bit number to a 3 byte RGB space. I see nothing wrong with just taking the low 3 bytes.

int hash = string.getHashCode();
int r = (hash & 0xFF0000) >> 16;
int g = (hash & 0x00FF00) >> 8;
int b = hash & 0x0000FF;

这篇关于将字符串转换为RGB颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆