Convert a RGB Color Value to a Hexadecimal String

前端 未结 4 1937
南旧
南旧 2020-11-30 01:06

In my Java application, I was able to get the Color of a JButton in terms of red, green and blue; I have stored these values in three int

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 01:27

    A one liner but without String.format for all RGB colors:

    Color your_color = new Color(128,128,128);
    
    String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);
    

    You can add a .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

    When you have ARGB colors you can use:

    Color your_color = new Color(128,128,128,128);
    
    String buf = Integer.toHexString(your_color.getRGB());
    String hex = "#"+buf.substring(buf.length()-6);
    

    A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format():

提交回复
热议问题