diff --git a/src/util/color_reader.py b/src/util/color_reader.py index 0f81283..e5a9263 100644 --- a/src/util/color_reader.py +++ b/src/util/color_reader.py @@ -16,7 +16,7 @@ def closest_colour_rgb(requested_color): return min_colours[min(min_colours.keys())] -def get_rgb_color_name(color): +def rgb2color_name(color): try: closest_name = actual_name = rgb_to_name(color, 'html4') except ValueError: @@ -28,7 +28,7 @@ def get_rgb_color_name(color): return closest_name -def get_hex_color_name(color): +def hex2color_name(color): try: color = hex_to_rgb(color) except ValueError: @@ -56,7 +56,7 @@ def str2closest_html_color_name(s: str): return '' if len(rgb) != 3: return '' - name = get_rgb_color_name(rgb) + name = rgb2color_name(rgb) return name elif '#' in s: @@ -66,7 +66,7 @@ def str2closest_html_color_name(s: str): return 'olive' if s in ['#B0DFD7', '#EFF8F6', '#5CC4B7']: return 'teal' - name = get_hex_color_name(s) + name = hex2color_name(s) if (name == 'white') and (s.lower() not in ['#ffffff', '#fff']): name = 'gray' @@ -83,28 +83,22 @@ def str2hex(s: str): 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 + match = re.search(r'rgba*\(((\d+)%, *(\d+)%, *(\d+)%(, \d\.\d+)*)\)', s) + if match: + r, g, b = int(match.group(2)), int(match.group(3)), int(match.group(4)) + return rgb_percent_to_hex((r, g, b)) 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 + match = re.search(r'rgba*\(((\d+), *(\d+), *(\d+)(, \d\.\d+)*)\)', s) + if match: + r, g, b = int(match.group(2)), int(match.group(3)), int(match.group(4)) + return rgb_to_hex((r, g, b)) 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) + 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, s, l = int(match.group(2)), int(match.group(3)), int(match.group(4)) h /= 360 s /= 10 l /= 100 @@ -119,8 +113,6 @@ def str2hex(s: str): if __name__ == '__main__': - str2color_name('rgb(139, 0, 0)') - colors = [ (75, 0, 130), (255, 0, 255), (139, 69, 19), (46, 139, 87), @@ -132,10 +124,10 @@ if __name__ == '__main__': ] for c in colors: - n = get_rgb_color_name(c) + n = rgb2color_name(c) print("Actual colour:", c, ", closest colour name:", n) for c in hex_colors: - n = get_hex_color_name(c) + n = hex2color_name(c) print("Actual colour:", c, ", closest colour name:", n) print()