2014-01-20 176 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) } –