Skip to content

Commit 5a78f44

Browse files
SethFalcoSeth Falco
authored and
Seth Falco
committed
Added algorithm for color contrast ratio.
1 parent ca2e207 commit 5a78f44

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Misc/ColorContrastRatio.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package Misc;
2+
3+
/**
4+
* A Java implementation of the offcial W3 documented procedure
5+
* to calculate contrast ratio between colors on the web.
6+
*
7+
* @since 2020-10-15
8+
* @see <a href="https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-procedure">Color Contrast Ratio Procedure</a>
9+
* @author Seth Falco (https://elypia.org/)
10+
*/
11+
public class ColorContrastRatio {
12+
13+
/**
14+
* Calculates the contrast ratio between two given colors.
15+
*
16+
* @param a Any color, used to get the red, green, and blue values.
17+
* @param b Another color, which will be compared against the first color.
18+
* @return The contrast ratio between the two colors.
19+
*/
20+
public double getContrastRatio(Color a, Color b) {
21+
final double aColorLuminance = getRelativeLuminance(a);
22+
final double bColorLuminance = getRelativeLuminance(b);
23+
24+
if (aColorLuminance > bColorLuminance)
25+
return (aColorLuminance + 0.05) / (bColorLuminance + 0.05);
26+
else
27+
return (bColorLuminance + 0.05) / (aColorLuminance + 0.05);
28+
}
29+
30+
/**
31+
* Calculates the relative luminance of a given color.
32+
*
33+
* @param color Any color, used to get the red, green, and blue values.
34+
* @return The relative luminance of the color.
35+
* @see <a href="https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef">More info on relative luminance.</a>
36+
*/
37+
public double getRelativeLuminance(Color color) {
38+
final double red = getColor(color.getRed());
39+
final double green = getColor(color.getGreen());
40+
final double blue = getColor(color.getBlue());
41+
42+
return 0.2126 * red + 0.7152 * green + 0.0722 * blue;
43+
}
44+
45+
/**
46+
* Calculates the final value for a color to be used in the
47+
* relative luminance formula as described in step 1.
48+
*
49+
* @param color8Bit The 8-bit repretation of a color component value.
50+
* @return Value for the provided color component to be used in the relative luminance formula.
51+
*/
52+
public double getColor(int value) {
53+
final double sRgb = getColorSRgb(value);
54+
return (sRgb <= 0.03928) ? sRgb / 12.92 : Math.pow((sRgb + 0.055) / 1.055, 2.4);
55+
}
56+
57+
/**
58+
* Calculates the Color sRGB value as denoted in step 1
59+
* of the procedure document.
60+
*
61+
* @param color8Bit The 8-bit repretation of a color component value.
62+
* @return A percentile value of the color component.
63+
*/
64+
private double getColorSRgb(double color8Bit) {
65+
return color8Bit / 255.0;
66+
}
67+
}

0 commit comments

Comments
 (0)