misc: add rgb-luminance related utils (#77644)
gitea/publik-django-templatetags/pipeline/head This commit looks good
Details
gitea/publik-django-templatetags/pipeline/head This commit looks good
Details
This commit is contained in:
parent
b458b1ceb1
commit
5753d9d2b7
|
@ -196,3 +196,19 @@ def duration(value, arg='short'):
|
|||
except (TypeError, ValueError):
|
||||
return ''
|
||||
return utils.seconds2humanduration(int(value.total_seconds()), short=bool(arg != 'long'))
|
||||
|
||||
|
||||
@register.filter
|
||||
def luminance(rgb):
|
||||
red = int(rgb[1:3], base=16)
|
||||
green = int(rgb[3:5], base=16)
|
||||
blue = int(rgb[5:7], base=16)
|
||||
# Y’ from ITU-R BT.709 conversion:
|
||||
return red * 0.2126 + green * 0.7152 + blue * 0.0722
|
||||
|
||||
|
||||
@register.filter
|
||||
def get_foreground_color(background_rgb):
|
||||
# where background_rgb is a #xxyyzz hex RBG color value.
|
||||
# the 128 luminance threshold is picked to match w.c.s. WF status display logic:
|
||||
return 'white' if luminance(background_rgb) < 128 else 'black'
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
from django.template import Context, Template
|
||||
from pytest import raises
|
||||
|
||||
|
||||
def test_get():
|
||||
|
@ -359,3 +360,27 @@ def test_duration():
|
|||
context = Context({'value': 'xx'})
|
||||
assert Template('{{ value|duration }}').render(context) == ''
|
||||
assert Template('{{ value|duration:"long" }}').render(context) == ''
|
||||
|
||||
|
||||
def test_luminance():
|
||||
context = Context({'value': '#8c22ec'})
|
||||
assert Template('{{ value|luminance }}').render(context) == '71.12'
|
||||
|
||||
context = Context({'value': '#f0d343'})
|
||||
assert Template('{{ value|luminance }}').render(context) == '206.7686'
|
||||
|
||||
context = Context({'value': '#8c22'})
|
||||
with raises(ValueError):
|
||||
Template('{{ value|luminance }}').render(context)
|
||||
|
||||
|
||||
def test_get_foreground_color():
|
||||
context = Context({'value': '#8c22ec'})
|
||||
assert Template('{{ value|get_foreground_color }}').render(context) == 'white'
|
||||
|
||||
context = Context({'value': '#f0d343'})
|
||||
assert Template('{{ value|get_foreground_color }}').render(context) == 'black'
|
||||
|
||||
context = Context({'value': '#8c22'})
|
||||
with raises(ValueError):
|
||||
Template('{{ value|get_foreground_color }}').render(context)
|
||||
|
|
Loading…
Reference in New Issue