-
Expression-based Contrast Ratio Calculator
Hi! I’m trying to write an expression that’ll take two hex color codes (for now I just have it grabbing them from text layers), determine their Relative Luminances, and then compare them to determine the Contrast Ratio between them.
The part that’s tripping me up- I’m pretty sure- is converting After Effects’s sRGB 2.2 values to linear RGB, since I keep getting the wrong Relative Luminance. Can anybody tell where I’m screwing things up in this expression?
//Relative luminance of color 1
txt1 = thisComp.layer("Color1NoTag").text.sourceText;
hex1 = parseInt(txt1,16);
r1 = hex1 >> 16;
g1 = (hex1 & 0x00ff00) >> 8;
b1 = hex1 & 0xff;
if ((r1/255) <= 0.03928) {
rConv1 = (r1/255)/12.92;
}
if ((g1/255) <= 0.03928) {
gConv1 = (g1/255)/12.92;
}
if ((b1/255)<= 0.03928) {
bConv1 = (b1/255)/12.92;
}
if ((r1/255) > 0.03928) {
rConv1 = ((r1/255)+0.055)^2.4;
}
if ((g1/255) > 0.03928) {
gConv1 = ((g1/255)+0.055)^2.4;
}
if ((b1/255) > 0.03928) {
bConv1 = ((b1/255)+0.055)^2.4;
}
rel1 = ((rConv1/255)*0.2126)+((gConv1/255)*0.7152)+((bConv1/255)*0.0722);//Relative luminance of color 2
txt2 = thisComp.layer("Color2NoTag").text.sourceText;
hex2 = parseInt(txt2,16);
r2 = hex2 >> 16;
g2 = (hex2 & 0x00ff00) >> 8;
b2 = hex2 & 0xff;
if ((r2/255) <= 0.03928) {
rConv2 = (r2/255)/12.92;
}
if ((g2/255) <= 0.03928) {
gConv2 = (g2/255)/12.92;
}
if ((b2/255)<= 0.03928) {
bConv2 = (b2/255)/12.92;
}
if ((r2/255) > 0.03928) {
rConv2 = ((r2/255)+0.055)^2.4;
}
if ((g2/255) > 0.03928) {
gConv2 = ((g2/255)+0.055)^2.4;
}
if ((b2/255) > 0.03928) {
bConv2 = ((b2/255)+0.055)^2.4;
}
rel2 = ((rConv2/255)*0.2126)+((gConv2/255)*0.7152)+((bConv2/255)*0.0722);//Contrast Ratio
(Math.round((rel1+0.05)/(rel2+0.05)*100)/100) +":1"