Skip to content

Instantly share code, notes, and snippets.

@rautamiekka
Created November 13, 2016 19:03
Show Gist options
  • Save rautamiekka/989d644a4982a73b4919516d8dad39dc to your computer and use it in GitHub Desktop.
Save rautamiekka/989d644a4982a73b4919516d8dad39dc to your computer and use it in GitHub Desktop.
Calculate difference in percentage between 2 hex colors
"""
This function is a direct Python 2.7+ translation of
https://gist.github.com/mailtruck/2411659
Will exit if executed without importing.
--rautamiekka
"""
if __name__ == '__main__':
from sys import exit as sysexit
sysexit(1)
def color_meter(cwith, ccolor):
if not cwith or len(str(cwith)) != 7 or not ccolor or len(str(ccolor)) != 7:
raise ValueError(
"Either of the parameters is not 7-digit integer."
)
_cwith = int(str(cwith)[1:7]) if str(cwith)[0] == "#" else cwith
_ccolor = int(str(ccolor)[1:7]) if str(ccolor)[0] == "#" else ccolor
_r = int(str(_cwith)[0:2], 16)
_g = int(str(_cwith)[2:4], 16)
_b = int(str(_cwith)[4:6], 16)
__r = int(str(_ccolor)[0:2], 16)
__g = int(str(_ccolor)[2:4], 16)
__b = int(str(_ccolor)[4:6], 16)
p1 = _r / 255 * 100
p2 = _g / 255 * 100
p3 = _b / 255 * 100
perc1 = int(
round(
(p1 + p2 + p3) / 3,
0
)
)
p1 = __r / 255 * 100
p2 = __g / 255 * 100
p3 = __b / 255 * 100
perc2 = int(
round(
(p1 + p2 + p3) / 3,
0
)
)
return abs(perc1 - perc2)
@gdog1986
Copy link

gdog1986 commented Jan 24, 2018

I'm not that experienced with Python yet, however I found that running this code returns 0
print p1 inside definitioncode was also returning 0
I have placed floats around the r, g and b codes. like so:

    p1 = float(_r) / 255 * 100
    p2 = float(_g) / 255 * 100
    p3 = float(_b) / 255 * 100
    p1 = float(__r) / 255 * 100
    p2 = float(__g) / 255 * 100
    p3 = float(__b) / 255 * 100

now print p1 returns 135
print color_meter('#84D9A3','#144024') returns 11.89543

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment