วิธีแปลง hex เป็น rgb โดยใช้ Java


99

ฉันจะแปลงสีฐานสิบหกเป็นรหัส RGB ใน Java ได้อย่างไร ส่วนใหญ่ใน Google ตัวอย่างเป็นวิธีการแปลงจาก RGB เป็นฐานสิบหก


คุณสามารถยกตัวอย่างสิ่งที่คุณกำลังพยายามแปลงและสิ่งที่คุณกำลังพยายามจะแปลงได้หรือไม่ ยังไม่ชัดเจนว่าคุณกำลังพยายามทำอะไร
kkress

000000 จะเปลี่ยนเป็น rgb สีดำ
user236501

คำตอบ:


164

ฉันเดาว่าควรทำ:

/**
 * 
 * @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

294

จริงๆแล้วมีวิธีที่ง่ายกว่า (ในตัว) ในการทำสิ่งนี้:

Color.decode("#FFCCEE");

3
น่าเสียดายที่เป็น AWT: /
wuppi

6
@wuppi ฉันคิดว่านั่นเป็นข่าวดีจริงๆเนื่องจาก AWT อยู่ใน JDK โชคร้ายอะไรเกี่ยวกับเรื่องนี้?
Dmitry Avtonomov

19
โซลูชันที่ยอมรับยังใช้ AWT AWT ไม่ใช่ปัญหาสำหรับผู้ถามเดิม นี่ควรเป็นทางออกที่ได้รับการยอมรับ
jewbix.cube

6
บน Android: Color.parseColor ()
Dawid Drozd


27

สำหรับการพัฒนาAndroidฉันใช้:

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

เพียงแค่แทนที่ "#" ด้วย "0x"
Julian Os

1
Color.parseColor ไม่รองรับสีที่มีตัวเลขสามหลักเช่นนี้
#fff

คุณสามารถลองด้านล่างของ #fff int red = colorString.charAt (1) == '0'? 0: 255; int สีน้ำเงิน = colorString.charAt (2) == '0'? 0: 255; int สีเขียว = colorString.charAt (3) == '0'? 0: 255; Color.rgb (แดงเขียวน้ำเงิน);
GTID

10

นี่คือเวอร์ชันที่รองรับทั้ง 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 ดูเหมือนจะไม่ทำงานกับมัน
เทด

4

รหัสสีฐานสิบหกคือ #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;
}

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


1

แปลงเป็นจำนวนเต็มจากนั้น divmod สองครั้งด้วย 16, 256, 4096 หรือ 65536 ขึ้นอยู่กับความยาวของสตริงฐานสิบหกเดิม (3, 6, 9 หรือ 12 ตามลำดับ)


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

สำหรับผู้ใช้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
}

0
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 : "");
}

ฉันคิดว่างานนี้จะ



-1

เมื่อวันก่อนฉันได้แก้ปัญหาที่คล้ายกันและพบว่าสะดวกในการแปลงสตริงสีฐานสิบหกเป็นอาร์เรย์ 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.