【问题标题】:Compute hex color code for an arbitrary string计算任意字符串的十六进制颜色代码
【发布时间】:2011-01-28 17:10:07
【问题描述】:

标题

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

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()));
}

【问题讨论】:

  • 任何六位十六进制代码都不是有效的 RGB 颜色吗?
  • 我认为这是真的,每个 RGB 颜色分量的范围是 0-256。任何 2 个 HEX 数字加在一起将产生最多 256 个数字。

标签: java ruby colors hex


【解决方案1】:

如果您并不真正关心颜色的“含义”,您可以将 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));
}

【讨论】:

  • C# private string StringToARGB(string text) { int i = text.GetHashCode(); return "#" + (((i &gt;&gt; 24) &amp; 0xFF)).ToString("X2") + (((i &gt;&gt; 16) &amp; 0xFF)).ToString("X2") + (((i &gt;&gt; 8) &amp; 0xFF)).ToString("X2") + ((i &amp; 0xFF)).ToString("X2"); } 也是如此,您可以像这样创建一个 Color 对象:Color color = (Color)(new ColorConverter()).ConvertFromString(this.StringToARGB(source));
【解决方案2】:

我在寻找 Ruby 解决方案时遇到了这个问题,所以我想我会为 Ruby 添加一个答案,以防有人遵循与我相同的路径。我最终使用了以下方法,该方法使用String.hashFixnum.to_s 的可选基本指定参数从字符串创建相同的六位十六进制代码。它从 1 而不是 0 切分以跳过负号。

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

【讨论】:

    【解决方案3】:

    andhashcode0x00FFFFFF(或 0xFFFFFF,如果您想默认 Alpha 通道)怎么样?例如:

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

    【讨论】:

      【解决方案4】:

      如果其他人正在寻找 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);
          }
      

      【讨论】:

        【解决方案5】:

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

        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));
            }
          }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2014-10-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-27
          • 2017-04-14
          • 2011-10-25
          • 2012-08-16
          相关资源
          最近更新 更多