001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.awt.Color;
005import java.util.Locale;
006
007/**
008 * Helper to convert from color to HTML string and back.
009 */
010public final class ColorHelper {
011
012    private ColorHelper() {
013        // Hide default constructor for utils classes
014    }
015
016    /**
017     * Returns the {@code Color} for the given HTML code.
018     * @param html the color code
019     * @return the color
020     */
021    public static Color html2color(String html) {
022        if (!html.isEmpty() && html.charAt(0) == '#')
023            html = html.substring(1);
024        if (html.length() == 3) {
025            return html2color(new String(
026                    new char[]{html.charAt(0), html.charAt(0), html.charAt(1), html.charAt(1), html.charAt(2), html.charAt(2)}));
027        }
028        if (html.length() != 6 && html.length() != 8)
029            return null;
030        try {
031            return new Color(
032                    Integer.parseInt(html.substring(0, 2), 16),
033                    Integer.parseInt(html.substring(2, 4), 16),
034                    Integer.parseInt(html.substring(4, 6), 16),
035                    html.length() == 8 ? Integer.parseInt(html.substring(6, 8), 16) : 255);
036        } catch (NumberFormatException e) {
037            return null;
038        }
039    }
040
041    private static String int2hex(int i) {
042        String s = Integer.toHexString(i / 16) + Integer.toHexString(i % 16);
043        return s.toUpperCase(Locale.ENGLISH);
044    }
045
046    /**
047     * Returns the HTML color code (6 or 8 digit).
048     * @param col The color to convert
049     * @return the HTML color code (6 or 8 digit)
050     */
051    public static String color2html(Color col) {
052        return color2html(col, true);
053    }
054
055    /**
056     * Returns the HTML color code (6 or 8 digit).
057     * @param col The color to convert
058     * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
059     * @return the HTML color code (6 or 8 digit)
060     * @since 6655
061     */
062    public static String color2html(Color col, boolean withAlpha) {
063        if (col == null)
064            return null;
065        String code = '#'+int2hex(col.getRed())+int2hex(col.getGreen())+int2hex(col.getBlue());
066        if (withAlpha) {
067            int alpha = col.getAlpha();
068            if (alpha < 255) {
069                code += int2hex(alpha);
070            }
071        }
072        return code;
073    }
074}