[英]Convert a RGB Color Value to a Hexadecimal String
在我的 Java 應用程序中,我能夠以紅色、綠色和藍色的形式獲得JButton
的Color
; 我已將這些值存儲在三個int
中。
如何將這些 RGB 值轉換為包含等效十六進制表示的String
? 如#0033fA
您可以使用
String hex = String.format("#%02x%02x%02x", r, g, b);
如果您希望將生成的十六進制數字大寫( #FFFFFF
vs. #ffffff
),請使用大寫 X。
一個襯里,但沒有適用於所有RGB顏色的String.format
:
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);
理論上,一個班輪也是可能的,但需要調用 toHexString 兩次。 我對 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;
即使 alpha 通道值為零(例如0000ff
),也將java.awt.Color
轉換為 24 位十六進制 RGB 表示:
String.format("%06x", 0xFFFFFF & Color.BLUE.getRGB())
對於大寫(例如0000FF
):
String.format("%06X", 0xFFFFFF & Color.BLUE.getRGB())
這是Vivien Barousse給出的答案的改編版本,應用了Vulcan的更新。 在此示例中,我使用滑塊從三個滑塊中動態檢索 RGB 值並在矩形中顯示該顏色。 然后在 toHex() 方法中,我使用這些值創建顏色並顯示相應的十六進制顏色代碼。
此示例不包括 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;
}
}
非常感謝 Vivien 和 Vulcan。 該解決方案完美運行,實施起來超級簡單。
How to convert a color integer to a hex String in Android? 對 RGBA 的略微修改版本? 以及如何將 RGB 編碼和解碼為十六進制
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;
}
一個非常簡單的基准測試表明,對於 1000 萬次顏色轉換,使用 String.format 的解決方案比 StringBuilder 慢 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,我們需要所有數字才能獲得有效的十六進制顏色值,如果使用 Alpha,則為 6 或 8。 據我所知,我們需要改進使用 Integer.toHexString 來處理這些情況。 應該有其他情況無法處理十六進制值的前導零。 例如,嘗試使用對應於Color color = new Color(12,12,12,12);
的#0c0c0c0c
結果將是#C0C0C0C 女巫是錯誤的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.