How to convert hex to rgb using Java?

后端 未结 19 1938
-上瘾入骨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 14:10

    you can do it simply as below:

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

    For Example

    getRGB("444444") = 68,68,68   
    getRGB("FFFFFF") = 255,255,255
    
    0 讨论(0)
  • 2020-11-27 14:11

    For Android development, I use:

    int color = Color.parseColor("#123456");
    
    0 讨论(0)
  • 2020-11-27 14:12

    Convert it to an integer, then divmod it twice by 16, 256, 4096, or 65536 depending on the length of the original hex string (3, 6, 9, or 12 respectively).

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

    For Android Kotlin users:

    "#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
    }
    
    0 讨论(0)
  • 2020-11-27 14:15
    public static void main(String[] args) {
        int hex = 0x123456;
        int r = (hex & 0xFF0000) >> 16;
        int g = (hex & 0xFF00) >> 8;
        int b = (hex & 0xFF);
    }
    
    0 讨论(0)
  • 2020-11-27 14:15
    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);
    
    0 讨论(0)
提交回复
热议问题