16進、Color、Colour変換

8345 ワード

 1 import java.awt.Color;  2 import jxl.format.Colour;  3  4 public class ColorUtil {  6 public static Colour getNearestColour(Color awtColor) {  7 Colour color = null;  8  9 Colour[] colors = Colour.getAllColours(); 10 if ((colors != null) && (colors.length > 0)) { 11 Colour crtColor = null; 12 int[] rgb = null; 13 int diff = 0; 14 int minDiff = 999; 15 16 for (int i = 0; i < colors.length; i++) { 17 crtColor = colors[i]; 18 rgb = new int[3]; 19 rgb[0] = crtColor.getDefaultRGB().getRed(); 20 rgb[1] = crtColor.getDefaultRGB().getGreen(); 21 rgb[2] = crtColor.getDefaultRGB().getBlue(); 22 23 diff = Math.abs(rgb[0] - awtColor.getRed()) 24 + Math.abs(rgb[1] - awtColor.getGreen()) 25 + Math.abs(rgb[2] - awtColor.getBlue()); 26 27 if (diff < minDiff) { 28 minDiff = diff; 29 color = crtColor; 30  } 31  } 32  } 33 if (color == null) 34 color = Colour.BLACK; 35 return color; 36  } 37 //Color 16  38 public static String toHexEncoding(Color color) { 39  String R, G, B; 40 StringBuffer sb = new StringBuffer(); 41 42 R = Integer.toHexString(color.getRed()); 43 G = Integer.toHexString(color.getGreen()); 44 B = Integer.toHexString(color.getBlue()); 45 46 R = R.length() == 1 ? "0" + R : R; 47 G = G.length() == 1 ? "0" + G : G; 48 B = B.length() == 1 ? "0" + B : B; 49 50 sb.append("0x"); 51  sb.append(R); 52  sb.append(G); 53  sb.append(B); 54 55 return sb.toString(); 56  } 57 58 // java.awt.Color 59 public static Color parseToColor(final String c) { 60 Color convertedColor = Color.ORANGE; 61 try { 62 convertedColor = new Color(Integer.parseInt(c, 16)); 63 } catch(NumberFormatException e) { 64 // codes to deal with this exception 65  } 66 return convertedColor; 67  } 68 public static Colour getColour(final String c) { 69 Color cl=parseToColor(c); 70 return getNearestColour(cl); 71  } 72 // 73 }