forked from LiveCarta/BookConverter
epub converter: add color conversion, update adding style tags
This commit is contained in:
87
src/util/color_reader.py
Normal file
87
src/util/color_reader.py
Normal file
@@ -0,0 +1,87 @@
|
||||
from webcolors import html4_hex_to_names, hex_to_rgb, rgb_to_name
|
||||
|
||||
|
||||
def closest_colour_rgb(requested_colour):
|
||||
min_colours = {}
|
||||
for key, name in html4_hex_to_names.items():
|
||||
r_c, g_c, b_c = hex_to_rgb(key)
|
||||
rd = (r_c - requested_colour[0]) ** 2
|
||||
gd = (g_c - requested_colour[1]) ** 2
|
||||
bd = (b_c - requested_colour[2]) ** 2
|
||||
min_colours[(rd + gd + bd)] = name
|
||||
|
||||
return min_colours[min(min_colours.keys())]
|
||||
|
||||
|
||||
def get_rgb_colour_name(c):
|
||||
try:
|
||||
closest_name = actual_name = rgb_to_name(c, 'html4')
|
||||
except ValueError:
|
||||
closest_name = closest_colour_rgb(c)
|
||||
actual_name = None
|
||||
if actual_name:
|
||||
return actual_name
|
||||
else:
|
||||
return closest_name
|
||||
|
||||
|
||||
def get_hex_colour_name(c):
|
||||
try:
|
||||
c = hex_to_rgb(c)
|
||||
except ValueError:
|
||||
return ''
|
||||
|
||||
try:
|
||||
closest_name = actual_name = rgb_to_name(c, 'html4')
|
||||
except ValueError:
|
||||
closest_name = closest_colour_rgb(c)
|
||||
actual_name = None
|
||||
if actual_name:
|
||||
return actual_name
|
||||
else:
|
||||
return closest_name
|
||||
|
||||
|
||||
def str2color_name(s: str):
|
||||
if 'rgb' in s:
|
||||
s = s.replace('rgb', '').replace('(', '').replace(')', '')
|
||||
try:
|
||||
rgb = [int(x) for x in s.split(',')]
|
||||
rgb = tuple(rgb)
|
||||
except ValueError:
|
||||
return ''
|
||||
if len(rgb) != 3:
|
||||
return ''
|
||||
name = get_rgb_colour_name(rgb)
|
||||
return name
|
||||
|
||||
elif '#' in s:
|
||||
name = get_hex_colour_name(s)
|
||||
return name
|
||||
|
||||
else:
|
||||
return ''
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
str2color_name('rgb(139, 0, 0)')
|
||||
|
||||
colors = [
|
||||
(75, 0, 130), (255, 0, 255),
|
||||
(139, 69, 19), (46, 139, 87),
|
||||
(221, 160, 221)
|
||||
]
|
||||
|
||||
hex_colors = [
|
||||
'#96F', '#000', '#4C4C4C', '#A00', '#99F'
|
||||
]
|
||||
|
||||
for c in colors:
|
||||
name = get_rgb_colour_name(c)
|
||||
print("Actual colour:", c, ", closest colour name:", name)
|
||||
|
||||
for c in hex_colors:
|
||||
name = get_hex_colour_name(c)
|
||||
print("Actual colour:", c, ", closest colour name:", name)
|
||||
print()
|
||||
Reference in New Issue
Block a user