-
Notifications
You must be signed in to change notification settings - Fork 0
/
imagetools.py
59 lines (45 loc) · 1.79 KB
/
imagetools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import PIL
import colorthief
import PIL.Image
import colorsys
import sys
def get_gradient_colors(image_path):
'''Find a fitting tile gradient for a given image'''
first_color = "blue"
# prefer a color if image has a consistent outer color #
try:
image = PIL.Image.open(image_path)
pixels = image.load()
except PIL.UnidentifiedImageError as e:
print(e, file=sys.stderr)
return("orange", "purple")
max_x, max_y = image.size
color_left = pixels[int(max_x/2), 0]
color_top = pixels[0, int(max_y/2)]
color_right = pixels[max_x-1, int(max_y/2)]
color_bottom = pixels[int(max_x/2), max_y-1]
# check all colors the same #
if len(set([color_left, color_top, color_right, color_bottom])) == 1:
try:
return build_brightness_gradient(color_left, brighten_color(*color_left))
except TypeError as e:
print("WARN:", e, file=sys.stderr)
# find a dominant color otherwies #
color_thief = colorthief.ColorThief(image_path)
dominant_color = color_thief.get_color(quality=1)
palette = color_thief.get_palette(color_count=2)
if len(palette) < 2:
return build_brightness_gradient(dominant_color, palette[1])
return build_brightness_gradient(palette[0], palette[1])
def build_brightness_gradient(color_left, color_right):
return (rgba_to_string(*color_left), rgba_to_string(*color_right))
def brighten_color(r, g, b, a=255):
'''Generate the second part of the gradient'''
h, l, s = colorsys.rgb_to_hls(r,g,b)
new_color = colorsys.hls_to_rgb(h, max(1, l)*1.5, s=s)
# handle transparent pictures
if a == 0:
return *new_color, 0.5
return new_color
def rgba_to_string(r, g, b, a=255):
return "rgba({r},{g},{b},{a})".format(r=r, g=g, b=b, a=a)