【问题标题】:How to convert hex to rgb using Java?如何使用 Java 将十六进制转换为 rgb?
【发布时间】:2011-05-06 23:48:24
【问题描述】:

如何在 Java 中将十六进制颜色转换为 RGB 代码?大多数在 Google 中,示例是关于如何从 RGB 转换为十六进制。

【问题讨论】:

  • 您能否举例说明您要转换的内容以及您要转换的内容?目前尚不清楚您要做什么。
  • 000000 将转换为黑色 rgb

标签: java colors


【解决方案1】:

实际上,有一种更简单(内置)的方法:

Color.decode("#FFCCEE");

【讨论】:

  • 不幸的是 AWT :/
  • @wuppi 我认为这实际上是个好消息,因为 AWT 在 JDK 中。有什么不好的?
  • 公认的解决方案也使用 AWT。对于原始提问者来说,AWT 不是问题。这应该是公认的解决方案。
  • 在安卓上:Color.parseColor()
【解决方案2】:

我想应该这样做:

/**
 * 
 * @param colorStr e.g. "#FFFFFF"
 * @return 
 */
public static Color hex2Rgb(String colorStr) {
    return new Color(
            Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
            Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
            Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}

【讨论】:

  • 对于那些也想要 3 个字符版本的人,请注意,在 3 个字符的情况下,每个值必须是 * 255 / 16。我用“000”、“aaa”和“fff”进行了测试",现在它们都可以正常工作了。
【解决方案3】:
public static void main(String[] args) {
    int hex = 0x123456;
    int r = (hex & 0xFF0000) >> 16;
    int g = (hex & 0xFF00) >> 8;
    int b = (hex & 0xFF);
}

【讨论】:

    【解决方案4】:

    对于 Android 开发,我使用:

    int color = Color.parseColor("#123456");
    

    【讨论】:

    • 只需将 '#' 替换为 '0x'
    • Color.parseColor 不支持这样的三位数颜色:#fff
    • 你可以试试下面的 #fff int red = colorString.charAt(1) == '0' 吗? 0:255; int blue = colorString.charAt(2) == '0' ? 0:255; int green = colorString.charAt(3) == '0' ? 0:255; Color.rgb(红、绿、蓝);
    【解决方案5】:

    这是一个同时处理 RGB 和 RGBA 版本的版本:

    /**
     * Converts a hex string to a color. If it can't be converted null is returned.
     * @param hex (i.e. #CCCCCCFF or CCCCCC)
     * @return Color
     */
    public static Color HexToColor(String hex) 
    {
        hex = hex.replace("#", "");
        switch (hex.length()) {
            case 6:
                return new Color(
                Integer.valueOf(hex.substring(0, 2), 16),
                Integer.valueOf(hex.substring(2, 4), 16),
                Integer.valueOf(hex.substring(4, 6), 16));
            case 8:
                return new Color(
                Integer.valueOf(hex.substring(0, 2), 16),
                Integer.valueOf(hex.substring(2, 4), 16),
                Integer.valueOf(hex.substring(4, 6), 16),
                Integer.valueOf(hex.substring(6, 8), 16));
        }
        return null;
    }
    

    【讨论】:

    • 这对我很有用,因为 Integer.toHexString 支持 alpha 通道,但 Integer.decode 或 Color.decode 似乎不适用于它。
    【解决方案6】:

    你可以这样做:

     public static int[] getRGB(final String rgb)
    {
        final int[] ret = new int[3];
        for (int i = 0; i < 3; i++)
        {
            ret[i] = Integer.parseInt(rgb.substring(i * 2, i * 2 + 2), 16);
        }
        return ret;
    }
    

    举例

    getRGB("444444") = 68,68,68   
    getRGB("FFFFFF") = 255,255,255
    

    【讨论】:

    • 漂亮! Xackly 我需要的!丹克!
    【解决方案7】:

    十六进制颜色代码是#RRGGBB

    RR、GG、BB 是 0-255 范围内的十六进制值

    让我们调用 RR XY 其中 X 和 Y 是十六进制字符 0-9A-F, A=10, F=15

    十进制值为X*16+Y

    如果 RR = B7,则 B 的小数点为 11,因此值为 11*16 + 7 = 183

    public int[] getRGB(String rgb){
        int[] ret = new int[3];
        for(int i=0; i<3; i++){
            ret[i] = hexToInt(rgb.charAt(i*2), rgb.charAt(i*2+1));
        }
        return ret;
    }
    
    public int hexToInt(char a, char b){
        int x = a < 65 ? a-48 : a-55;
        int y = b < 65 ? b-48 : b-55;
        return x*16+y;
    }
    

    【讨论】:

      【解决方案8】:

      对于 JavaFX

      import javafx.scene.paint.Color;
      

      .

      Color whiteColor = Color.valueOf("#ffffff");
      

      【讨论】:

        【解决方案9】:

        将其转换为整数,然后根据原始十六进制字符串的长度(分别为 3、6、9 或 12)将其 divmod 两次 16、256、4096 或 65536。

        【讨论】:

          【解决方案10】:

          很多这些解决方案都有效,但这是一个替代方案。

          String hex="#00FF00"; // green
          long thisCol=Long.decode(hex)+4278190080L;
          int useColour=(int)thisCol;
          

          如果您不添加 4278190080 (#FF000000),颜色的 Alpha 为 0 并且不会显示。

          【讨论】:

            【解决方案11】:

            对于 Android Kotlin 开发人员:

            "#FFF".longARGB()?.let{ Color.parceColor(it) }
            "#FFFF".longARGB()?.let{ Color.parceColor(it) }
            
            fun String?.longARGB(): String? {
                if (this == null || !startsWith("#")) return null
                
            //    #RRGGBB or #AARRGGBB
                if (length == 7 || length == 9) return this
            
            //    #RGB or #ARGB
                if (length in 4..5) {
                    val rgb = "#${this[1]}${this[1]}${this[2]}${this[2]}${this[3]}${this[3]}"
                    if (length == 5) {
                        return "$rgb${this[4]}${this[4]}"
                    }
                    return rgb
                }
            
                return null
            }
            

            【讨论】:

              【解决方案12】:

              要详细说明@xhh 提供的答案,您可以在返回之前附加红色、绿色和蓝色以将字符串格式化为“rgb(0,0,0)”。

              /**
              * 
              * @param colorStr e.g. "#FFFFFF"
              * @return String - formatted "rgb(0,0,0)"
              */
              public static String hex2Rgb(String colorStr) {
                  Color c = new Color(
                      Integer.valueOf(hexString.substring(1, 3), 16), 
                      Integer.valueOf(hexString.substring(3, 5), 16), 
                      Integer.valueOf(hexString.substring(5, 7), 16));
              
                  StringBuffer sb = new StringBuffer();
                  sb.append("rgb(");
                  sb.append(c.getRed());
                  sb.append(",");
                  sb.append(c.getGreen());
                  sb.append(",");
                  sb.append(c.getBlue());
                  sb.append(")");
                  return sb.toString();
              }
              

              【讨论】:

                【解决方案13】:

                如果你不想使用 AWT Color.decode,那么只需复制方法的内容:

                int i = Integer.decode("#FFFFFF");
                int[] rgb = new int[]{(i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF};
                

                Integer.decode 处理 # 或 0x,具体取决于字符串的格式

                【讨论】:

                  【解决方案14】:

                  这是另一个处理 RGBA 版本的更快版本:

                  public static int hexToIntColor(String hex){
                      int Alpha = Integer.valueOf(hex.substring(0, 2), 16);
                      int Red = Integer.valueOf(hex.substring(2, 4), 16);
                      int Green = Integer.valueOf(hex.substring(4, 6), 16);
                      int Blue = Integer.valueOf(hex.substring(6, 8), 16);
                      Alpha = (Alpha << 24) & 0xFF000000;
                      Red = (Red << 16) & 0x00FF0000;
                      Green = (Green << 8) & 0x0000FF00;
                      Blue = Blue & 0x000000FF;
                      return Alpha | Red | Green | Blue;
                  }
                  

                  【讨论】:

                    【解决方案15】:

                    最简单的方法:

                    // 0000FF
                    public static Color hex2Rgb(String colorStr) {
                        return new Color(Integer.valueOf(colorStr, 16));
                    }
                    

                    【讨论】:

                      【解决方案16】:
                      public static Color hex2Rgb(String colorStr) {
                          try {
                              // Create the color
                              return new Color(
                                      // Using Integer.parseInt() with a radix of 16
                                      // on string elements of 2 characters. Example: "FF 05 E5"
                                      Integer.parseInt(colorStr.substring(0, 2), 16),
                                      Integer.parseInt(colorStr.substring(2, 4), 16),
                                      Integer.parseInt(colorStr.substring(4, 6), 16));
                          } catch (StringIndexOutOfBoundsException e){
                              // If a string with a length smaller than 6 is inputted
                              return new Color(0,0,0);
                          }
                      }
                      
                      public static String rgbToHex(Color color) {
                          //      Integer.toHexString(), built in Java method        Use this to add a second 0 if the
                          //     .Get the different RGB values and convert them.     output will only be one character.
                          return Integer.toHexString(color.getRed()).toUpperCase() + (color.getRed() < 16 ? 0 : "") + // Add String
                                  Integer.toHexString(color.getGreen()).toUpperCase() + (color.getGreen() < 16 ? 0 : "") +
                                  Integer.toHexString(color.getBlue()).toUpperCase() + (color.getBlue() < 16 ? 0 : "");
                      }
                      

                      我认为这会奏效。

                      【讨论】:

                        【解决方案17】:

                        十六进制颜色代码已经是 rgb。格式为#RRGGBB

                        【讨论】:

                        • 除非是#RGB、#RRRGGGBBB 或#RRRRGGGGBBBB。
                        【解决方案18】:

                        前几天我一直在解决类似的问题,发现将十六进制颜色字符串转换为 int 数组 [alpha, r, g, b] 很方便:

                         /**
                         * Hex color string to int[] array converter
                         *
                         * @param hexARGB should be color hex string: #AARRGGBB or #RRGGBB
                         * @return int[] array: [alpha, r, g, b]
                         * @throws IllegalArgumentException
                         */
                        
                        public static int[] hexStringToARGB(String hexARGB) throws IllegalArgumentException {
                        
                            if (!hexARGB.startsWith("#") || !(hexARGB.length() == 7 || hexARGB.length() == 9)) {
                        
                                throw new IllegalArgumentException("Hex color string is incorrect!");
                            }
                        
                            int[] intARGB = new int[4];
                        
                            if (hexARGB.length() == 9) {
                                intARGB[0] = Integer.valueOf(hexARGB.substring(1, 3), 16); // alpha
                                intARGB[1] = Integer.valueOf(hexARGB.substring(3, 5), 16); // red
                                intARGB[2] = Integer.valueOf(hexARGB.substring(5, 7), 16); // green
                                intARGB[3] = Integer.valueOf(hexARGB.substring(7), 16); // blue
                            } else hexStringToARGB("#FF" + hexARGB.substring(1));
                        
                            return intARGB;
                        }
                        

                        【讨论】:

                          【解决方案19】:
                          For shortened hex code like #fff or #000
                          
                          int red = "colorString".charAt(1) == '0' ? 0 : 
                               "colorString".charAt(1) == 'f' ? 255 : 228;  
                          int green =
                               "colorString".charAt(2) == '0' ? 0 :  "colorString".charAt(2) == 'f' ?
                               255 : 228;  
                          int blue = "colorString".charAt(3) == '0' ? 0 : 
                               "colorString".charAt(3) == 'f' ? 255 : 228;
                          
                          Color.rgb(red, green,blue);
                          

                          【讨论】:

                          • #eee 怎么样?
                          猜你喜欢
                          • 2015-05-09
                          • 2011-05-14
                          • 2011-08-09
                          • 2020-11-14
                          • 2013-07-10
                          • 2015-01-31
                          • 2021-03-22
                          相关资源
                          最近更新 更多