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