2014-01-20 80 views
2

如果我有一個Color對象,如何將其RGB值轉換爲十六進制整數?我一直在尋找年齡,所有我發現的是「十六進制到RGB」,或者它不返回一個整數值,或其他我不想要的東西。將RGB轉換爲十六進制

我希望它返回十六進制值作爲int值,而不是字符串或其他任何東西。誰能幫忙?

這裏是我的代碼,我需要一個顏色轉換爲十六進制,使用別人的答案,嘗試將其轉換:

public static void loadImageGraphics(BufferedImage image, int x, int y, int width, int height) { 
    for(int yy = 0; yy < height; yy++) { 
     for(int xx = 0; xx < width; xx++) { 
      Color c = new Color(image.getRGB(xx, yy)); 
      pixels[x + y * width] = c.getRed() * (0xFF)^2 + c.getGreen() * 0xFF + c.getBlue(); 
     } 
    } 
} 

謝謝!

+1

一個整數,僅僅是一個值。將其轉換爲字符串時,它只會變成十六進制表示形式。 – Henry

+0

其他解決方案這裏http://stackoverflow.com/questions/3607858/how-to-convert-a-rgb-color-value-to-an-hexadecimal-value-in-java – gowtham

回答

3

此實用程序功能是爲我工作的罰款:

public static String convertColorToHexadeimal(Color color) 
{ 
     String hex = Integer.toHexString(color.getRGB() & 0xffffff); 
     if(hex.length() < 6) 
     { 
      if(hex.length()==5) 
       hex = "0" + hex; 
      if(hex.length()==4) 
       hex = "00" + hex; 
      if(hex.length()==3) 
       hex = "000" + hex; 
     } 
     hex = "#" + hex; 
     return hex; 
} 
+0

這將返回一個字符串。我試圖添加一個'Integer.parseInt()',但是我得到一個'NumberFormatException'。 – sparklyllama

+0

@sparklyllama:你可以在base-16中寫入一個整數,就像'0xffffff'是'16777215'。 – Blender

+0

顏色c = Color.RED; 字符串十六進制= convertColorToHexadeimal(c); System.out.println(「hex:」+ hex); 字符串hexRed = hex.substring(0,2); 字符串hexGreen = hex.substring(2,4); 字符串hexBlue = hex.substring(4,6); System.out.println(convert(hexRed)); System.out.println(convert(hexGreen)); System.out.println(convert(hexBlue));公共靜態int轉換(字符串n) 返回Integer.valueOf(n,16) } –