计算任意字符串的十六进制颜色代码

发布于 2024-08-25 03:45:28 字数 375 浏览 6 评论 0 原文

标题

有没有办法将任意字符串映射到十六进制颜色代码。我尝试使用字符串哈希码计算字符串的十六进制数。现在我需要将此十六进制数字转换为十六进制颜色代码范围内的六位数字。有什么建议吗?

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + Integer.toHexString(programs[i].hashCode()));
}

Heading

Is there a way to map an arbitrary string to a HEX COLOR code. I tried to compute the HEX number for string using string hashcode. Now I need to convert this hex number to six digits which are in HEX color code range. Any suggestions ?

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + Integer.toHexString(programs[i].hashCode()));
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

还不是爱你 2024-09-01 03:45:29

我在寻找 Ruby 解决方案时遇到了这个问题,所以我想我应该为 Ruby 添加一个答案,以防有人遵循与我相同的路径。我最终使用了以下方法,该方法通过使用 String.hash 以及 Fixnum.to_s。它从 1 而不是 0 进行切片以跳过负号。

def color_from_string(query)
  '#'+query.hash.to_s(16).slice(1,6)
end

I ran into this question while looking for a Ruby solution, so I thought I would add an answer for Ruby in case someone follows the same path I did. I ended up using the following method, which creates the same six digit hex code from a string by using String.hash and the optional base-specifying parameter of Fixnum.to_s. It slices from 1 rather than 0 to skip negative signs.

def color_from_string(query)
  '#'+query.hash.to_s(16).slice(1,6)
end
时光礼记 2024-09-01 03:45:29

下面的类接受一个字符串并将其转换为颜色。
它是 Color-Hash TypeScript 项目(MIT 许可证)的简化 Java 端口:https://github。 com/zenozeng/color-hash
原始项目包含一些参数来调整生成的颜色。
这些不包括在内。

与直接使用哈希值相比,颜色哈希算法的优点是生成的颜色在感知上更加均匀。

这里进行了大量的复制/粘贴:

结果:

XYZ: #bf40b3
TEST1: #86432d
TEST2: #3a2dd2
TEST3: #bf4073
SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS: #53ac8b
public class ColorHash
{

  private static final double[] LigthnessArray  = new double[] { 0.35, 0.5, 0.65 };
  private static final double[] SaturationArray = new double[] { 0.35, 0.5, 0.65 };

  public Color generateColor(String input) throws NoSuchAlgorithmException
  {
    // Easiest way would be String.hashCode()
    // But "Test1" and "Test2" result in practically the same color
    // Therefore another hash algorithm should be used
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(input.getBytes());
    byte[] digest = md.digest();
    int hash = Math.abs(ByteBuffer.wrap(digest).getInt());

    double hue, saturation, lightness;

    hue = hash % 359 / 359.; // note that 359 is a prime
    hash = (int) Math.ceil(hash / 360);
    saturation = SaturationArray[hash % SaturationArray.length];
    hash = (int) Math.ceil(hash / SaturationArray.length);
    lightness = LigthnessArray[hash % LigthnessArray.length];

    return hslColor((float) hue, (float) saturation, (float) lightness);
  }

  public String generateColorHash(String input) throws NoSuchAlgorithmException
  {
    return "#" + Integer.toHexString(generateColor(input).getRGB()).substring(2);
  }

  private static Color hslColor(float h, float s, float l)
  {
    float q, p, r, g, b;

    if (s == 0)
    {
      r = g = b = l; // achromatic
    } else
    {
      q = l < 0.5 ? (l * (1 + s)) : (l + s - l * s);
      p = 2 * l - q;
      r = hue2rgb(p, q, h + 1.0f / 3);
      g = hue2rgb(p, q, h);
      b = hue2rgb(p, q, h - 1.0f / 3);
    }
    return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
  }

  private static float hue2rgb(float p, float q, float h)
  {
    if (h < 0)
    {
      h += 1;
    }

    if (h > 1)
    {
      h -= 1;
    }

    if (6 * h < 1) { return p + ((q - p) * 6 * h); }
    if (2 * h < 1) { return q; }
    if (3 * h < 2) { return p + ((q - p) * 6 * ((2.0f / 3.0f) - h)); }

    return p;
  }
  
  public static void main(String[] args) throws NoSuchAlgorithmException
  {
    String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};
    ColorHash gen = new ColorHash();
    for(String p : programs) {
      System.out.println(p + ": " + gen.generateColorHash(p));
    }
  }

}

The following class takes a String and converts it to a color.
It is a simplified Java port of the Color-Hash TypeScript project (MIT license): https://github.com/zenozeng/color-hash.
The original project contains some parameters to adjust the generated colours.
These were not included.

The advantage of the Color-Hash algorithm, compared using a hash value directly, is that the generated colours are more perceptually uniform.

A lot of copy/paste was going on here:

Result:

XYZ: #bf40b3
TEST1: #86432d
TEST2: #3a2dd2
TEST3: #bf4073
SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS: #53ac8b
public class ColorHash
{

  private static final double[] LigthnessArray  = new double[] { 0.35, 0.5, 0.65 };
  private static final double[] SaturationArray = new double[] { 0.35, 0.5, 0.65 };

  public Color generateColor(String input) throws NoSuchAlgorithmException
  {
    // Easiest way would be String.hashCode()
    // But "Test1" and "Test2" result in practically the same color
    // Therefore another hash algorithm should be used
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(input.getBytes());
    byte[] digest = md.digest();
    int hash = Math.abs(ByteBuffer.wrap(digest).getInt());

    double hue, saturation, lightness;

    hue = hash % 359 / 359.; // note that 359 is a prime
    hash = (int) Math.ceil(hash / 360);
    saturation = SaturationArray[hash % SaturationArray.length];
    hash = (int) Math.ceil(hash / SaturationArray.length);
    lightness = LigthnessArray[hash % LigthnessArray.length];

    return hslColor((float) hue, (float) saturation, (float) lightness);
  }

  public String generateColorHash(String input) throws NoSuchAlgorithmException
  {
    return "#" + Integer.toHexString(generateColor(input).getRGB()).substring(2);
  }

  private static Color hslColor(float h, float s, float l)
  {
    float q, p, r, g, b;

    if (s == 0)
    {
      r = g = b = l; // achromatic
    } else
    {
      q = l < 0.5 ? (l * (1 + s)) : (l + s - l * s);
      p = 2 * l - q;
      r = hue2rgb(p, q, h + 1.0f / 3);
      g = hue2rgb(p, q, h);
      b = hue2rgb(p, q, h - 1.0f / 3);
    }
    return new Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
  }

  private static float hue2rgb(float p, float q, float h)
  {
    if (h < 0)
    {
      h += 1;
    }

    if (h > 1)
    {
      h -= 1;
    }

    if (6 * h < 1) { return p + ((q - p) * 6 * h); }
    if (2 * h < 1) { return q; }
    if (3 * h < 2) { return p + ((q - p) * 6 * ((2.0f / 3.0f) - h)); }

    return p;
  }
  
  public static void main(String[] args) throws NoSuchAlgorithmException
  {
    String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};
    ColorHash gen = new ColorHash();
    for(String p : programs) {
      System.out.println(p + ": " + gen.generateColorHash(p));
    }
  }

}
坚持沉默 2024-09-01 03:45:29

如果其他人正在寻找 Flutter/Dart 的解决方案:

    Color _fromInt(int i) {
      final a = (i >> 24) & 0xFF;
      final r = (i >> 16) & 0xFF;
      final g = (i >> 8) & 0xFF;
      final b = i & 0xFF;
      return Color.fromARGB(a, r, g, b);
    }

还值得注意的是,对于某些背景颜色(例如黑色),可能很难区分颜色。

为此,我将 Alpha 通道设置为最大值 255:

    Color _fromInt(int i) {
      const a = 255;
      final r = (i >> 16) & 0xFF;
      final g = (i >> 8) & 0xFF;
      final b = i & 0xFF;
      return Color.fromARGB(a, r, g, b);
    }

In case anyone else is looking for a solution for Flutter/Dart:

    Color _fromInt(int i) {
      final a = (i >> 24) & 0xFF;
      final r = (i >> 16) & 0xFF;
      final g = (i >> 8) & 0xFF;
      final b = i & 0xFF;
      return Color.fromARGB(a, r, g, b);
    }

It's also worth noting that with certain background colours e.g. black, it may be difficult to differentiate the colours.

To this end, I set the alpha channel to the max value of 255:

    Color _fromInt(int i) {
      const a = 255;
      final r = (i >> 16) & 0xFF;
      final g = (i >> 8) & 0xFF;
      final b = i & 0xFF;
      return Color.fromARGB(a, r, g, b);
    }
a√萤火虫的光℡ 2024-09-01 03:45:28

如果你并不真正关心颜色的“含义”,你可以只分割 int 的位(删除第一个仅用于 RGB 而不是 ARGB)

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + intToARGB(programs[i].hashCode()));
}
....
public static String intToARGB(int i){
    return Integer.toHexString(((i>>24)&0xFF))+
        Integer.toHexString(((i>>16)&0xFF))+
        Integer.toHexString(((i>>8)&0xFF))+
        Integer.toHexString((i&0xFF));
}

If you don't really care about the "meaning" of the color you can just split up the bits of the int (remove the first for just RGB instead of ARGB)

String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"};

for(int i = 0; i < programs.length; i++) {
  System.out.println( programs[i] + " -- " + intToARGB(programs[i].hashCode()));
}
....
public static String intToARGB(int i){
    return Integer.toHexString(((i>>24)&0xFF))+
        Integer.toHexString(((i>>16)&0xFF))+
        Integer.toHexString(((i>>8)&0xFF))+
        Integer.toHexString((i&0xFF));
}
强辩 2024-09-01 03:45:28

怎么样使用0x00FFFFFF(或0xFFFFFF,如果你想默认alpha通道)来hashcode?例如:

private String getColorCode(String inputString)
{
    String colorCode = String.format("#%06x", 0xFFFFFF & inputString.hashCode());
}

How about anding the hashcode with 0x00FFFFFF (or 0xFFFFFF if you want to default the alpha channel)? For example:

private String getColorCode(String inputString)
{
    String colorCode = String.format("#%06x", 0xFFFFFF & inputString.hashCode());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文