How to convert hex to rgb using Java?

后端 未结 19 1939
-上瘾入骨i
-上瘾入骨i 2020-11-27 13:46

How can I convert hex color to RGB code in Java? Mostly in Google, samples are on how to convert from RGB to hex.

相关标签:
19条回答
  • 2020-11-27 13:56

    I guess this should do it:

    /**
     * 
     * @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 ) );
    }
    
    0 讨论(0)
  • 2020-11-27 13:57

    Hexidecimal color codes are already rgb. The format is #RRGGBB

    0 讨论(0)
  • 2020-11-27 13:59
    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 : "");
    }
    

    I think that this wil work.

    0 讨论(0)
  • 2020-11-27 14:00

    For JavaFX

    import javafx.scene.paint.Color;
    

    .

    Color whiteColor = Color.valueOf("#ffffff");
    
    0 讨论(0)
  • 2020-11-27 14:00

    If you don't want to use the AWT Color.decode, then just copy the contents of the method:

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

    Integer.decode handles the # or 0x, depending on how your string is formatted

    0 讨论(0)
  • 2020-11-27 14:04

    Actually, there's an easier (built in) way of doing this:

    Color.decode("#FFCCEE");
    
    0 讨论(0)
提交回复
热议问题