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