001 // License: GPL. Copyright 2007 by Immanuel Scholz and others 002 package org.openstreetmap.josm.tools; 003 004 import java.awt.Color; 005 006 /** 007 * Helper to convert from color to html string and back 008 */ 009 public class ColorHelper { 010 011 public static Color html2color(String html) { 012 if (html.length() > 0 && html.charAt(0) == '#') 013 html = html.substring(1); 014 if (html.length() != 6 && html.length() != 8) 015 return null; 016 try { 017 return new Color( 018 Integer.parseInt(html.substring(0,2),16), 019 Integer.parseInt(html.substring(2,4),16), 020 Integer.parseInt(html.substring(4,6),16), 021 (html.length() == 8 ? Integer.parseInt(html.substring(6,8),16) : 255)); 022 } catch (NumberFormatException e) { 023 return null; 024 } 025 } 026 027 private static String int2hex(int i) { 028 String s = Integer.toHexString(i / 16) + Integer.toHexString(i % 16); 029 return s.toUpperCase(); 030 } 031 032 public static String color2html(Color col) { 033 if (col == null) 034 return null; 035 return "#"+int2hex(col.getRed())+int2hex(col.getGreen())+int2hex(col.getBlue()); 036 } 037 }