有没有办法判断HTML十六进制颜色是浅还是暗

cod*_*441 4 html java jsp

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

我在我的页面中使用了jsp.有没有办法说出这样的话

如果颜色<## 0686FF,则fontcolour =#000000例如

编辑:寻找scriptlet或javascript

Dun*_*nes 11

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

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

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
}
Run Code Online (Sandbox Code Playgroud)

HSB代表色调,饱和度,亮度 - 亮度也称为亮度.Color类的值介于1和0之间.Ergo,0.5亮度是最亮颜色和最暗颜色之间的中间点.

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


pee*_*nut 10

"颜色"通常表示24位RGB颜色:红色,绿色,蓝色为1字节(8位).也就是说,每个通道在十六进制显示中的值为0-255或0x00到0xff.

白色是所有通道:#FFFFFF,黑色是所有通道关闭:#000000.显然,较浅的颜色意味着较高的通道值,较暗的颜色意味着较低的通道值.

你如何选择你的算法取决于你,简单的是:

//pseudo-code
if (red + green + blue <= (0xff * 3) / 2) //half-down, half-up
  fontcolor = white;
else
  fontcolor = black;
Run Code Online (Sandbox Code Playgroud)

编辑:提问者要求更完整的例子,所以他/她可以有更好的开始,所以这里是:

public static void main(String[] args) throws IOException {

String value =
       // new Scanner(System.in).nextLine(); //from input
        "#112233"; //from constant
int red = Integer.parseInt(value.substring(1, 1 + 2), 16);
int green = Integer.parseInt(value.substring(3, 3 + 2), 16);
int blue = Integer.parseInt(value.substring(5, 5 + 2), 16);

System.out.println("red = " + Integer.toHexString(red)
        + ", green = " + Integer.toHexString(green)
        + ", blue = " + Integer.toHexString(blue));

if (red + green + blue <= 0xff * 3 / 2)
    System.out.println("using white color #ffffff");
else
    System.out.println("using black color #000000");

String colorBackToString = "#" + Integer.toHexString(red) +
        Integer.toHexString(green) +
        Integer.toHexString(blue);
System.out.println("color was " + colorBackToString);
}
Run Code Online (Sandbox Code Playgroud)

它产生输出:

red = 11, green = 22, blue = 33
using white color #ffffff
color was #112233

并显示了将#aabbcc格式的颜色分割为rgb通道,稍后加入它们(如果需要)等技术.