programing

RGB 색상 값을 16진수 문자열로 변환

projobs 2022. 10. 11. 22:00
반응형

RGB 색상 값을 16진수 문자열로 변환

자바 어플리케이션에서, 나는 그 어플리케이션을 얻을 수 있었습니다.ColorJButton에 이 했습니다.ints.

을 RGB로 해야 합니까?String열여섯 살?를 들면, 「」등#0033fA

사용할 수 있습니다.

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

합니다.#FFFFFF ★★#ffffff를 참조해 주세요.

의 라이너로 되어 , ★★★★★★★★★★★★★★★★★★★★★★★★★★ 없음String.format모든 RGB 색상:

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

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

해서 '어울리지 않다'를 수 있어요..toUpperCase()이치노이것은 모든 RGB 색상에 유효합니다(질문에 기재된 바와 같이).

ARGB 색상이 있는 경우 다음을 사용할 수 있습니다.

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

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

이론적으로는 1개의 라이너도 가능하지만 HexString에 2회 호출해야 합니다. 용액을 ARGB 용액과 했습니다.String.format()toHexString솔루션이 훨씬 더 높은 성능을 발휘합니다.

여기에 이미지 설명 입력

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;

java.awt.Color RGB "0" "24" "16" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "RGB" "0" "RGB" "RGB" "0" "0" "R" "R0000ff

String.format("%06x", 0xFFFFFF & Color.BLUE.getRGB())

대문자의 경우(예:0000FF

String.format("%06X", 0xFFFFFF & Color.BLUE.getRGB())

Vivien Barousse가 Vulcan에서 업데이트한 답변을 개작한 것입니다.이 예에서는 슬라이더를 사용하여 3개의 슬라이더에서 RGB 값을 동적으로 검색하여 직사각형으로 표시합니다.그런 다음 메서드 to Hex()에서는 값을 사용하여 색상을 만들고 각각의 16진수 색상 코드를 표시합니다.

이 예에는 GridBagLayout에 대한 적절한 제약 조건이 포함되어 있지 않습니다.코드는 작동하지만 디스플레이는 이상하게 보입니다.

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

비비안과 벌컨 둘 다에게 정말 고마워.이 솔루션은 완벽하게 작동하며 구현이 매우 간단했습니다.

Android에서 색정수를 16진수 문자열로 변환하는 방법에서 RGBA용으로 약간 수정된 버전?RGB를 16진수로 코드화 디코딩하는 방법

    public static String ColorToHex (Color color) {
    int red = color.getRed();
    int green = color.getGreen();
    int blue = color.getBlue();
    int alpha = color.getAlpha(); 

    String redHex = To00Hex(red);
    String greenHex = To00Hex(green);
    String blueHex = To00Hex(blue);
    String alphaHex = To00Hex(alpha);

    // hexBinary value: RRGGBBAA
    StringBuilder str = new StringBuilder("#");
    str.append(redHex);
    str.append(greenHex);
    str.append(blueHex);
    str.append(alphaHex);

    return str.toString();
}

private static String To00Hex(int value) {
    String hex = "00".concat(Integer.toHexString(value));
    hex=hex.toUpperCase();
    return hex.substring(hex.length()-2, hex.length());
} 

또 다른 방법으로, 이는 위의 벤치마크와 관련이 있을 수 있습니다.

public static String rgbToHex (Color color) {

   String hex = String.format("#%02x%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha() );
   hex=hex.toUpperCase();
       return hex;
}

매우 간단한 벤치마크는 String을 사용한 솔루션을 보여줍니다.포맷은 String Builder보다 2배 이상 느립니다.개체 수가 적은 경우에는 실제로 차이를 알 수 없습니다.

나는 전문가가 아니기 때문에 내 의견은 주관적이다.사용할 수 있도록 벤치마크 코드를 게시합니다. rgbToHex, rgbToHex2 메서드를 테스트하고 싶은 메서드로 대체하십시오.

   public static void benchmark /*ColorToHex*/ () {
       
 Color color = new Color(12,12,12,12);
   
     ArrayList<Color> colorlist = new ArrayList<Color>();
    // a list filled with a color i times
    for (int i = 0; i < 10000000; i++) {
      
        colorlist.add((color));
    }
   
   ArrayList<String> hexlist = new ArrayList<String>();
   System.out.println("START TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + "  TEST CASE 1...");
        for (int i = 0; i < colorlist.size(); i++) {
        hexlist.add(rgbToHex(colorlist.get(i)));
    }
        System.out.println("END TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + "  TEST CASE 1...");
        System.out.println("hexlist.get(0)... "+hexlist.get(0));
        
     ArrayList<String> hexlist2 = new ArrayList<String>();
   System.out.println("START TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + " TEST CASE 2...");
        for (int i = 0; i < colorlist.size(); i++) {
        hexlist2.add(rgbToHex1(colorlist.get(i)));
    }
     System.out.println("END TIME... " + ZonedDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) + "  TEST CASE 2..."); 
     System.out.println("hexlist2.get(0)... "+hexlist2.get(0));

    }

에 문제가 있는 것 같다Integer.toHexString(color.getRGB())와 함께 시도하다Color color = new Color(0,0,0,0);그러면 0을 빼는 방법이 있다는 것을 알게 될 것이다.#00000000이 아닌 #0. 유효한 16진수 값을 얻으려면 모든 숫자가 필요합니다.알파일 경우 6 또는 8입니다.이 경우 Integer.toHexString을 더 잘 사용해야 합니다.16진수 값에서 선행 0을 처리할 수 없는 다른 경우가 있을 것입니다.예를 들어,#0c0c0c0c에 대응하고 있다Color color = new Color(12,12,12,12);결과는 #C0C0C witch is wrong이 됩니다.

언급URL : https://stackoverflow.com/questions/3607858/convert-a-rgb-color-value-to-a-hexadecimal-string

반응형