Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to tell if a HTML hex colour is light or dark

Tags:

java

html

jsp

I want font colour on my html page to change to black if the background colour of the row is light and black if the background is white

I'm using jsp in my page. is there a way to say something like this

if colour < ##0686FF then fontcolour = #000000 for example

edit: looking for a scriptlet or javascript

like image 567
code511788465541441 Avatar asked Nov 27 '22 22:11

code511788465541441


1 Answers

This solution uses the java.awt.Color class to derive the brightness value of the colour and use that to determine which background colour should be used.

edit: This solution is differs from some of the other solutions because the other solutions will consider some bright colours to be dark eg. primary red (#FF0000). Whereas this solution, will consider primary red to be one of the brightest colours you can have. I suppose it depends on your preferences. Do you want to read red on black or red on white?

String fontColor = "#0cf356";

// remove hash character from string
String rawFontColor = fontColor.substring(1,fontColor.length());

// convert hex string to int
int rgb = Integer.parseInt(rawFontColor, 16);

Color c = new Color(rgb);

float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null);

float brightness = hsb[2];

if (brightness < 0.5) {
   // use a bright background
} else {
   // use a dark background
}

HSB stands for Hue, Saturation, Brightness -- brightness is also known as luminosity. With the Color class values are between 1 and 0. Ergo, 0.5 brightness is the the halfway point between the brightest colours and the darkest colours).

The interplay between hue, saturation and brightness are a little more complex than red, blue and green. Use this tool experiment with different colours and find the relationships between RGB and HSB

like image 123
Dunes Avatar answered Dec 28 '22 23:12

Dunes