Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...