Convert a RGB Color Value to a Hexadecimal String


88

Dalam aplikasi Java saya, saya bisa mendapatkan Color of a JButton in terms of red, green and blue; I have stored these values in three ints.

Bagaimana cara mengubah nilai RGB tersebut menjadi yang Stringmengandung representasi heksadesimal yang setara? Seperti#0033fA

Jawaban:


211

You can use

String hex = String.format("#%02x%02x%02x", r, g, b);  

Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF vs. #ffffff).


3
With input type 'Color': String.format("#%06x", Integer.valueOf(color.getRGB() & 0x00FFFFFF));
Stéphane Millien

Ini menghasilkanclass java.util.IllegalFormatConversionException with message: x != java.lang.Float
Mig82

@ smillien62: Saya yakin ini dapat disederhanakan menjadiString.format("#%06x", color.getRGB() & 0xFFFFFF);
MestreLion

@MestreLion, Dengan sintaks Anda, Anda memiliki peringatan karena Anda menggunakan "int", bukan "Integer".
Stéphane Millien

47

Satu liner tetapi tanpa String.formatuntuk semua warna RGB :

Color your_color = new Color(128,128,128);

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

Anda dapat menambahkan file .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

Jika Anda memiliki warna ARGB, Anda dapat menggunakan:

Color your_color = new Color(128,128,128,128);

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

Satu liner secara teoritis juga memungkinkan, tetapi perlu memanggil toHexString dua kali. Saya membandingkan solusi ARGB dan membandingkannya dengan String.format():

enter image description here


11
Ketahuilah bahwa metode ini rusak jika warna Anda memiliki nilai alfa <16 (yaitu representasi ARGB heksadesimalnya dimulai dengan 0).
ARRG

15
Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;

3
This answer fails in the case that the red or green values are zero (one example being Color.BLUE, which outputs #0ff because &'ing the RGB value of Color.BLUE results in 256 in base 10, which is ff in hex). A fix is to use a while loop rather than an if statement when preprending zeroes.
FThompson

1

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

Contoh ini tidak menyertakan batasan yang tepat untuk GridBagLayout. Meskipun kodenya akan berfungsi, tampilan akan terlihat aneh.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

Terima kasih banyak untuk Vivien dan Vulcan. Solusi ini bekerja dengan sempurna dan sangat mudah diterapkan.

Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.