Java를 사용하여 16 진수를 RGB로 변환하는 방법은 무엇입니까?


96

Java에서 16 진수 색상을 RGB 코드로 어떻게 변환 할 수 있습니까? 대부분 Google에서 샘플은 RGB에서 16 진수로 변환하는 방법에 대한 것입니다.


변환하려는 대상과 변환하려는 대상의 예를 제공 할 수 있습니까? 정확히 무엇을 하려는지 명확하지 않습니다.
— kkress

000000은 검은 색 rgb로 변환됩니다.
— user236501 2010

답변:


161

나는 이것이 그것을해야한다고 생각한다.

/**
 * 
 * @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"로 테스트했으며 이제 모두 제대로 작동합니다. .
— Andrew

283

실제로이 작업을 수행하는 더 쉬운 (내장) 방법이 있습니다.

Color.decode("#FFCCEE");

3
불행하게도 그 AWT입니다 /
— wuppi

6
@wuppi AWT가 JDK에 있기 때문에 실제로 좋은 소식이라고 생각했습니다. 그것에 대해 그렇게 불행한 것은 무엇입니까?
— Dmitry Avtonomov

19
허용되는 솔루션은 AWT도 사용합니다. AWT는 원래 질문자에게 문제가되지 않습니다. 이것이 허용되는 솔루션이어야합니다.
— jewbix.cube 2014-08-06

6
Color.parseColor () : 안드로이드
— DAWID 할 Drozd

37
public static void main(String[] args) {
    int hex = 0x123456;
    int r = (hex & 0xFF0000) >> 16;
    int g = (hex & 0xFF00) >> 8;
    int b = (hex & 0xFF);
}

26

들어 안드로이드 개발, 내가 사용 :

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

'#'을 '0x'로 바꾸십시오.
— Julian Os

1
Color.parseColor는 다음과 같은 세 자리 숫자의 색상을 지원하지 않습니다. #fff
— neoexpert

U 아래 #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 (빨간색, 녹색, 파란색);
— GTID

9

다음은 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이 알파 채널을 지원하기 때문에 이것은 나에게 유용했지만 Integer.decode 또는 Color.decode가 작동하지 않는 것 같습니다.
— Ted

4

16 진수 색상 코드는 #RRGGBB입니다.

RR, GG, BB는 0-255 범위의 16 진수 값입니다.

X와 Y가 16 진수 문자 0-9A-F, A = 10, F = 15 인 RR XY를 호출하겠습니다.

10 진수 값은 X * 16 + Y입니다.

RR = B7이면 B의 10 진수는 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;
}

4

다음과 같이 간단하게 할 수 있습니다.

 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

2

대한 자바 FX

import javafx.scene.paint.Color;

.

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

1

정수로 변환 한 다음 원래 16 진수 문자열 (각각 3, 6, 9 또는 12)의 길이에 따라 16, 256, 4096 또는 65536으로 두 번 divmod를 만듭니다.


1

이러한 솔루션이 많이 작동하지만 이것은 대안입니다.

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

4278190080 (# FF000000)을 추가하지 않으면 색상의 알파가 0이고 표시되지 않습니다.


0

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

0

AWT Color.decode를 사용하지 않으려면 메서드의 내용을 복사하면됩니다.

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

Integer.decode는 문자열 형식에 따라 # 또는 0x를 처리합니다.


0

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

0

가장 쉬운 방법 :

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


-1

다른 날에는 비슷한 문제를 해결하고 16 진수 색상 문자열을 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;
}

-1
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는 어떻습니까?
— Boni2k
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.