Saturday, February 18, 2017

Calculating contrast ratios of text

In a comment on my other article about how web pages are becoming hard to read, Shaun referenced the W3C Web Content Accessibility Guidelines. They provide an algorithm to determine if your text meets minimum accessibility guidelines.

The W3C definition of the contrast ratio requires several calculations: given two colors, you first compute the relative luminance of each (L1 and L2) then calculate the contrast ratio. The ratio will fall in the range 1 to 21 (typically written 1:1 or 21:1). The higher the contrast ratio, the more the text will stand out against the background. For example, black text on a white background has a contrast ratio of 21:1.

The W3C says body text should have a contrast ratio of at least 4.5:1, with headings at least 3:1. But that seems to be the bare minimum. The W3C also recommends at least 7:1 for body text and at least 4.5:1 for headings.

Calculating this can be a chore, so it's best to automate it. Shaum implemented the algorithm in XSLT so he could test the various colors in websites. I created a similar implementation using Bash. It's a little ugly, but I thought I'd share it here:

First, you need a way to input colors. I wanted something that could interpret different representations of colors: in html and css, black is the same as #000 or #000000 or rgb(0,0,0). When evaluating the readability of my text, I might want to use any of these.

Fortunately, there's a neat tool in GNOME to provide that input. GNOME Zenity is a scripting tool to display GTK+ dialogs. It supports many modes to read input and display results. One of the input modes is a color selector, which you use this way:
zenity --color-selection
You can give it other options to set the window title and provide a default color. Zenity returns the selected color on standard output. You can even set a default color. So to present two dialogs, one to read the text color and another to read the background color, you simply do this:
color=$( zenity --title 'Set text color' --color-selection --color='black' )
background=$( zenity --title 'Set background color' --color-selection --color='white' )
Zenity returns values like rgb(255,140,0) and rgb(255,255,255), which is fortunate because the W3C calculation for luminance requires values in the range 0 to 255. I wrote a simple function to pull apart the RGB values. There are probably simpler ways to parse RGB, but a quick and easy way is to let awk split the values at the comma. That means a value like rgb(255,140,0) gets split into rgb(255 and 140 and 0) so the R value is a substring starting at the fifth character, G is the second element, and B is a substring up to the last parenthesis.

Once I have the RGB values, then I calculate the luminance using bc. The funky math with e() and l() are to get around a limitation in bc. Specifically, the formula requires a fractional power, and bc can only do integer powers. But if you follow the math, you can get there using e() and l():
function luminance()
{
        R=$( echo $1 | awk -F, '{print substr($1,5)}' )
        G=$( echo $1 | awk -F, '{print $2}' )
        B=$( echo $1 | awk -F, '{n=length($3); print substr($3,1,n-1)}' )

        echo "scale=4
rsrgb=$R/255
gsrgb=$G/255
bsrgb=$B/255
if ( rsrgb <= 0.03928 ) r = rsrgb/12.92 else r = e( 2.4 * l((rsrgb+0.055)/1.055) )
if ( gsrgb <= 0.03928 ) g = gsrgb/12.92 else g = e( 2.4 * l((gsrgb+0.055)/1.055) )
if ( bsrgb <= 0.03928 ) b = bsrgb/12.92 else b = e( 2.4 * l((bsrgb+0.055)/1.055) )
0.2126 * r + 0.7152 * g + 0.0722 * b" | bc -l
}
Once you have the luminance value of the text color and background color, you can compute the contrast ratio. The W3C formula to do this is quite simple, but requires knowing which is the lighter and darker colors. This is an extra step in bc. I wrote this Bash function to calculate the ratio based on two colors:
function contrast()
{
        echo "scale=2
if ( $1 > $2 ) { l1=$1; l2=$2 } else { l1=$2; l2=$1 }
(l1 + 0.05) / (l2 + 0.05)" | bc
}
With those functions, it's fairly straightforward to write a Bash script that reads two colors, then computes the contrast ratio. My script also uses Zenity to output the data:
#!/bin/sh

# read color and background color:

color=$( zenity --title 'Set text color' --color-selection --color='black' )
if [ $? -ne 0 ] ; then
        echo '** color canceled - assume black'
        color='rgb(0,0,0)'
fi

background=$( zenity --title 'Set background color' --color-selection --color='white' )
if [ $? -ne 0 ] ; then
        echo '** background canceled - assume white'
        background='rgb(255,255,255)'
fi

# compute luminance:

function luminance()
{

}

lum1=$( luminance $color )
lum2=$( luminance $background )

# compute contrast

function contrast()
{

}

rel=$( contrast $lum1 $lum2 )

# print results

( echo "Color is $color on $background"
echo "Contrast ratio is $rel"

if [ ${rel%.*} -ge 4 ] ; then
        echo "Ok for body text"
else
        echo "Not good for body text"
fi
if [ ${rel%.*} -ge 3 ] ; then
        echo "Ok for title text"
else
        echo "Not good for title text"
fi) | zenity --text-info --title='Contrast Ratio'
With this script, I have a handy way to calculate the contrast ratio of two colors: text color vs background color. For black text on a white background, the contrast ratio is 21.00, the most visible. The #333 dark gray on white has a contrast ratio of 12.66, which is fine. And the lighter #808080 gray on white has a contrast ratio of 3.95, too low for normal text but acceptable for large text like headings. Very light #ccc gray on white has a contrast ratio of 1.60, which is way too low.

No comments:

Post a Comment