forked from LiveCarta/BookConverter
epub converter: fix color to all in hex
This commit is contained in:
@@ -1,4 +1,7 @@
|
||||
from webcolors import html4_hex_to_names, hex_to_rgb, rgb_to_name
|
||||
import re
|
||||
|
||||
from webcolors import html4_hex_to_names, hex_to_rgb, rgb_to_name, rgb_percent_to_hex, rgb_to_hex, css3_names_to_hex
|
||||
from colorsys import hls_to_rgb
|
||||
|
||||
|
||||
def closest_colour_rgb(requested_color):
|
||||
@@ -42,7 +45,7 @@ def get_hex_color_name(color):
|
||||
return closest_name
|
||||
|
||||
|
||||
def str2color_name(s: str):
|
||||
def str2closest_html_color_name(s: str):
|
||||
if 'rgb' in s:
|
||||
rgb_str = 'rgba' if ('rgba' in s) else 'rgb'
|
||||
s = s.replace(rgb_str, '').replace('(', '').replace(')', '')
|
||||
@@ -75,6 +78,45 @@ def str2color_name(s: str):
|
||||
return ''
|
||||
|
||||
|
||||
def str2hex(s: str):
|
||||
if '#' in s:
|
||||
return s
|
||||
|
||||
if ('rgb' in s) and ('%' in s):
|
||||
rgb_str = 'rgba' if ('rgba' in s) else 'rgb'
|
||||
s = s.replace(rgb_str, '').replace('(', '').replace(')', '')
|
||||
rgb_percent = s.split(',')[:3]
|
||||
hex_color = rgb_percent_to_hex(rgb_percent)
|
||||
return hex_color
|
||||
|
||||
if 'rgb' in s:
|
||||
rgb_str = 'rgba' if ('rgba' in s) else 'rgb'
|
||||
s = s.replace(rgb_str, '').replace('(', '').replace(')', '')
|
||||
try:
|
||||
rgb = [int(x) for x in s.split(',')[:3]]
|
||||
rgb = tuple(rgb)
|
||||
except ValueError:
|
||||
return ''
|
||||
hex_color = rgb_to_hex(rgb)
|
||||
return hex_color
|
||||
|
||||
if 'hsl' in s:
|
||||
# hsl(hue in {0,360}, saturation [0, 100%], lightness [0, 100%])
|
||||
match = re.search(r'hsla*\(((\d+), *(\d+)%, *(\d+)%(, \d\.\d)*)\)', s)
|
||||
if match:
|
||||
h, s, l = match.group(2), match.group(3), match.group(4)
|
||||
h /= 360
|
||||
s /= 10
|
||||
l /= 100
|
||||
rgb = tuple(hls_to_rgb(h, s, l))
|
||||
return rgb_to_hex(rgb)
|
||||
|
||||
if s.lower() in css3_names_to_hex:
|
||||
return css3_names_to_hex[s.lower()]
|
||||
|
||||
return ''
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
str2color_name('rgb(139, 0, 0)')
|
||||
|
||||
Reference in New Issue
Block a user