9b3b165adaaabc62953d7090bc5e4126de655242
[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     SHOULD_HAVE_ID = True
8
9     EPUB_TAG = HTML_TAG = 'img'
10
11     def get_html_attr(self, builder):
12         ## TODO: thumbnail.
13
14         url = six.moves.urllib.parse.urljoin(
15             builder.base_url,
16             self.get('src')
17         )
18         
19         imgfile = six.moves.urllib.request.urlopen(url)
20         img = Image.open(imgfile)
21         th_format, ext, media_type = {
22             'GIF': ('GIF', 'gif', 'image/gif'),
23             'PNG': ('PNG', 'png', 'image/png'),
24         }.get(img.format, ('JPEG', 'jpg', 'image/jpeg'))
25
26         width = 1200
27         if img.size[0] < width:
28             th = img
29         else:
30             th = img.resize((width, round(width * img.size[1] / img.size[0])))
31
32         buffer = six.BytesIO()
33         th.save(buffer, format=th_format)
34         imgfile.close()
35         file_name = 'image%d.%s' % (
36             builder.assign_image_number(),
37             ext
38         )
39
40         builder.add_file(
41             content=buffer.getvalue(),
42             file_name=file_name,
43             media_type=media_type,
44         )
45         
46         return {
47             'src': file_name,
48             'alt': self.attrib.get('alt', ''),
49             'title': self.attrib.get('alt', ''),
50         }
51
52     get_epub_attr = get_html_attr