Javaを使用してhexをrgbに変換する方法は?


96

Javaで16進数の色をRGBコードに変換するにはどうすればよいですか?ほとんどがGoogleで、サンプルはRGBから16進数に変換する方法です。


変換しようとしているものと変換しようとしているものの例を挙げられますか?あなたが何をしようとしているのか正確には分かりません。
kkress

000000は黒色のRGBに変換されます
user236501

回答:


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」でこれをテストしましたが、すべて正しく動作します。 。
アンドリュー

283

実際には、これを行う簡単な(組み込みの)方法があります。

Color.decode("#FFCCEE");

3
残念ながらそれはAWTです:/
wuppi

6
@wuppi AWTはJDKにあるので、これは実際に良いニュースだと思いました。それについて何がそんなに不幸なのですか?
ドミトリーアヴトノモフ2014年

19
承認済みのソリューションでもAWTを使用しています。AWTは元の質問者にとっては問題ではありません。これは受け入れられる解決策です。
jewbix.cube 2014

6
androidの場合:Color.parseColor()
Dawid

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

以下のためにAndroidの開発、私が使用します。

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

「#」を「0x」に置き換えるだけ
Julian Os

1
Color.parseColorは、次のような3桁の色をサポートしていません。#fff
neoexpert

以下の#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 2019年

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はアルファチャネルで動作しないため、これは私にとって便利でした。
テッド

4

16進数の色コードは#RRGGBBです。

RR、GG、BBは0〜255の範囲の16進値

RR XYを呼び出しましょう。ここで、XとYは16進文字0-9A-F、A = 10、F = 15です。

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

以下のためのJavaFX

import javafx.scene.paint.Color;

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


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.