fd8c764a9893f879ba22f4afbf1dbc62533ebe16
[librarian.git] / src / librarian / covers / widgets / background.py
1 import io
2 import time
3 from urllib.request import urlopen
4 import PIL.Image
5 from .base import Widget
6
7
8 class Background(Widget):
9     transparency = False
10
11     def __init__(self, cover, crop_to_square=True):
12         self.crop_to_square = crop_to_square
13         super().__init__(cover)
14
15     def setup(self):
16         self.img = None
17         if self.cover.book_info.cover_url:
18             while True:
19                 try:
20                     data = io.BytesIO(urlopen(self.cover.book_info.cover_url, timeout=3).read())
21                 except:
22                     time.sleep(2)
23                 else:
24                     break
25                 
26             img = PIL.Image.open(data)
27
28             if self.crop_to_square:
29                 # crop top square.
30                 if img.size[1] > img.size[0]:
31                     img = img.crop((0, 0, img.size[0], img.size[0]))
32                 else:
33                     left = round((img.size[0] - img.size[1])/2)
34                     img = img.crop((
35                         left,
36                         0,
37                         left + img.size[1],
38                         img.size[1]
39                     ))
40             self.img = img
41
42     def build(self, w, h):
43         if not self.img:
44             return
45         img = self.img
46         scale = max(
47             w / img.size[0],
48             h / img.size[1]
49         )
50         img = self.img.resize((
51             round(scale * img.size[0]),
52             round(scale * img.size[1]),
53         ))
54         img = img.crop((
55             int((img.size[0] - w) / 2),
56             0,
57             w + int((img.size[0] - w) / 2),
58             h))
59         
60         return img