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    /**
016     * Returns the {@code Color} for the given HTML code.
017     * @param html the color code
018     * @return the color
019     */
020    public static Color html2color(String html) {
021        if (html.length() > 0 && html.charAt(0) == '#')
022            html = html.substring(1);
023        if (html.length() == 3) {
024            return html2color(new String(
025                    new char[]{html.charAt(0), html.charAt(0), html.charAt(1), html.charAt(1), html.charAt(2), html.charAt(2)}));
026        }
027        if (html.length() != 6 && html.length() != 8)
028            return null;
029        try {
030            return new Color(
031                    Integer.parseInt(html.substring(0,2),16),
032                    Integer.parseInt(html.substring(2,4),16),
033                    Integer.parseInt(html.substring(4,6),16),
034                    (html.length() == 8 ? Integer.parseInt(html.substring(6,8),16) : 255));
035        } catch (NumberFormatException e) {
036            return null;
037        }
038    }
039
040    private static String int2hex(int i) {
041        String s = Integer.toHexString(i / 16) + Integer.toHexString(i % 16);
042        return s.toUpperCase();
043    }
044
045    /**
046     * Returns the HTML color code (6 or 8 digit).
047     * @param col The color to convert
048     * @return the HTML color code (6 or 8 digit)
049     */
050    public static String color2html(Color col) {
051        return color2html(col, true);
052    }
053
054    /**
055     * Returns the HTML color code (6 or 8 digit).
056     * @param col The color to convert
057     * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
058     * @return the HTML color code (6 or 8 digit)
059     * @since 6655
060     */
061    public static String color2html(Color col, boolean withAlpha) {
062        if (col == null)
063            return null;
064        String code = "#"+int2hex(col.getRed())+int2hex(col.getGreen())+int2hex(col.getBlue());
065        if (withAlpha) {
066            int alpha = col.getAlpha();
067            if (alpha < 255) {
068                code += int2hex(alpha);
069            }
070        }
071        return code;
072    }
073}