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