有没有办法判断HTML十六进制颜色是浅还是暗 [英] Is there a way to tell if a HTML hex colour is light or dark

查看:1325
本文介绍了有没有办法判断HTML十六进制颜色是浅还是暗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果背景颜色为白色,我希望我的html页面上的字体颜色变为黑色,如果背景为白色,我希望变为黑色

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

我正在使用我的页面中的jsp。有没有办法说这样的话

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

如果颜色< ## 0686FF然后fontcolour =#000000例如

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

编辑:寻找scriptlet或javascript

edit: looking for a scriptlet or javascript

推荐答案

此解决方案使用 java.awt.Color 类来派生颜色的亮度值,并使用它来确定应使用哪种背景颜色。

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.

编辑:此解决方案与其他一些解决方案不同,因为其他解决方案会将一些明亮的颜色视为黑暗,例如。初级红(#FF0000)。虽然这个解决方案,将主红色视为您可以拥有的最亮的颜色之一。我想这取决于你的喜好。你想在白色上读红色或红色吗?

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代表色调,饱和度,亮度 - 亮度也称为亮度。 Color类的值介于1和0之间.Ergo,0.5亮度是最亮颜色和最暗颜色之间的中间点。)

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).

色调之间的相互作用,饱和度和亮度比红色,蓝色和绿色稍微复杂一些。使用不同颜色的工具实验,找到RGB和HSB之间的关系

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

这篇关于有没有办法判断HTML十六进制颜色是浅还是暗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆