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

Last change on this file since 8404 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
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.awt.Color;
5import java.util.Locale;
6
7/**
8 * Helper to convert from color to HTML string and back.
9 */
10public final class ColorHelper {
11
12 private ColorHelper() {
13 // Hide default constructor for utils classes
14 }
15
16 /**
17 * Returns the {@code Color} for the given HTML code.
18 * @param html the color code
19 * @return the color
20 */
21 public static Color html2color(String html) {
22 if (html.length() > 0 && html.charAt(0) == '#')
23 html = html.substring(1);
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 }
28 if (html.length() != 6 && html.length() != 8)
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),
35 html.length() == 8 ? Integer.parseInt(html.substring(6,8),16) : 255);
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);
43 return s.toUpperCase(Locale.ENGLISH);
44 }
45
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 */
51 public static String color2html(Color col) {
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
58 * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
59 * @return the HTML color code (6 or 8 digit)
60 * @since 6655
61 */
62 public static String color2html(Color col, boolean withAlpha) {
63 if (col == null)
64 return null;
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;
73 }
74}
Note: See TracBrowser for help on using the repository browser.