New version with the new EPUB converter.
[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         imgfile.close()
31         buffer = six.BytesIO()
32         th.save(buffer, format=th_format)
33         ## TODO: Counter
34         file_name = 'image%d.%s' % (
35             builder.assign_image_number(),
36             ext
37         )
38
39         builder.add_file(
40             content=buffer.getvalue(),
41             file_name=file_name,
42             media_type=media_type,
43         )
44         
45         return {
46             'src': file_name,
47             'alt': self.attrib['alt'],
48             'title': self.attrib['alt'],
49         }
50
51     get_epub_attr = get_html_attr