Thema
[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 setup(self):
12         if self.cover.book_info.cover_url:
13             while True:
14                 try:
15                     data = io.BytesIO(urlopen(self.cover.book_info.cover_url, timeout=3).read())
16                 except:
17                     time.sleep(2)
18                 else:
19                     break
20                 
21             img = PIL.Image.open(data)
22
23             # crop top square.
24             if img.size[1] > img.size[0]:
25                 img = img.crop((0, 0, img.size[0], img.size[0]))
26             else:
27                 left = round((img.size[0] - img.size[1])/2)
28                 img = img.crop((
29                     left,
30                     0,
31                     left + img.size[1],
32                     img.size[1]
33                 ))
34             self.img = img
35
36     def build(self, w, h):
37         kwadrat = round(max(w, h))
38         img = self.img
39         img = self.img.resize((kwadrat, kwadrat))
40         img = img.crop((
41             int((img.size[0] - w) / 2),
42             0,
43             w + int((img.size[0] - w) / 2),
44             h))
45         
46         return img