Fixes for rare caces.
[librarian.git] / src / librarian / elements / figures / ilustr.py
1 import six.moves
2 from PIL import Image
3 from ..base import WLElement
4
5
6 class Ilustr(WLElement):
7     EPUB_TAG = HTML_TAG = 'img'
8
9     def get_html_attr(self, builder):
10         ## TODO: thumbnail.
11
12         url = six.moves.urllib.parse.urljoin(
13             builder.base_url,
14             self.get('src')
15         )
16         
17         imgfile = six.moves.urllib.request.urlopen(url)
18         img = Image.open(imgfile)
19         th_format, ext, media_type = {
20             'GIF': ('GIF', 'gif', 'image/gif'),
21             'PNG': ('PNG', 'png', 'image/png'),
22         }.get(img.format, ('JPEG', 'jpg', 'image/jpeg'))
23
24         width = 1200
25         if img.size[0] < width:
26             th = img
27         else:
28             th = img.resize((width, round(width * img.size[1] / img.size[0])))
29
30         buffer = six.BytesIO()
31         th.save(buffer, format=th_format)
32         imgfile.close()
33         file_name = 'image%d.%s' % (
34             builder.assign_image_number(),
35             ext
36         )
37
38         builder.add_file(
39             content=buffer.getvalue(),
40             file_name=file_name,
41             media_type=media_type,
42         )
43         
44         return {
45             'src': file_name,
46             'alt': self.attrib.get('alt', ''),
47             'title': self.attrib.get('alt', ''),
48         }
49
50     get_epub_attr = get_html_attr