source: josm/trunk/src/org/openstreetmap/josm/tools/ColorHelper.java@ 8414

Last change on this file since 8414 was 8404, checked in by Don-vip, 9 years ago

When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Lithuanian or Turkish. See PMD UseLocaleWithCaseConversions rule and String.toLowerCase() javadoc.

  • Property svn:eol-style set to native
File size: 2.4 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[75]2package org.openstreetmap.josm.tools;
3
4import java.awt.Color;
[8404]5import java.util.Locale;
[75]6
7/**
[6830]8 * Helper to convert from color to HTML string and back.
[75]9 */
[6362]10public final class ColorHelper {
[75]11
[6360]12 private ColorHelper() {
13 // Hide default constructor for utils classes
14 }
[6830]15
[6655]16 /**
17 * Returns the {@code Color} for the given HTML code.
18 * @param html the color code
19 * @return the color
20 */
[1169]21 public static Color html2color(String html) {
22 if (html.length() > 0 && html.charAt(0) == '#')
23 html = html.substring(1);
[6740]24 if (html.length() == 3) {
25 return html2color(new String(
26 new char[]{html.charAt(0), html.charAt(0), html.charAt(1), html.charAt(1), html.charAt(2), html.charAt(2)}));
27 }
[1371]28 if (html.length() != 6 && html.length() != 8)
[1169]29 return null;
30 try {
31 return new Color(
32 Integer.parseInt(html.substring(0,2),16),
33 Integer.parseInt(html.substring(2,4),16),
34 Integer.parseInt(html.substring(4,6),16),
[8345]35 html.length() == 8 ? Integer.parseInt(html.substring(6,8),16) : 255);
[1169]36 } catch (NumberFormatException e) {
37 return null;
38 }
39 }
40
41 private static String int2hex(int i) {
42 String s = Integer.toHexString(i / 16) + Integer.toHexString(i % 16);
[8404]43 return s.toUpperCase(Locale.ENGLISH);
[1169]44 }
45
[6655]46 /**
47 * Returns the HTML color code (6 or 8 digit).
48 * @param col The color to convert
49 * @return the HTML color code (6 or 8 digit)
50 */
[1169]51 public static String color2html(Color col) {
[6655]52 return color2html(col, true);
53 }
54
55 /**
56 * Returns the HTML color code (6 or 8 digit).
57 * @param col The color to convert
[6830]58 * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
[6655]59 * @return the HTML color code (6 or 8 digit)
60 * @since 6655
61 */
62 public static String color2html(Color col, boolean withAlpha) {
[3857]63 if (col == null)
64 return null;
[6655]65 String code = "#"+int2hex(col.getRed())+int2hex(col.getGreen())+int2hex(col.getBlue());
66 if (withAlpha) {
67 int alpha = col.getAlpha();
68 if (alpha < 255) {
69 code += int2hex(alpha);
70 }
71 }
72 return code;
[1169]73 }
[75]74}
Note: See TracBrowser for help on using the repository browser.