1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
8 from ..base import WLElement
11 MAX_PNG_WEIGHT = 200000
14 class Ilustr(WLElement):
17 EPUB_TAG = HTML_TAG = 'img'
19 def get_html_attr(self, builder):
22 url = urllib.parse.urljoin(
27 imgfile = urllib.request.urlopen(url)
28 img = Image.open(imgfile)
29 th_format, ext, media_type = {
30 'GIF': ('GIF', 'gif', 'image/gif'),
31 'PNG': ('PNG', 'png', 'image/png'),
32 }.get(img.format, ('JPEG', 'jpg', 'image/jpeg'))
35 if img.size[0] < width:
38 th = img.resize((width, round(width * img.size[1] / img.size[0])))
41 th.save(buffer, format=th_format)
43 # Limit PNG to 200K. If larger, convert to JPEG.
44 if th_format == 'PNG' and buffer.tell() > MAX_PNG_WEIGHT:
45 th_format, ext, media_type = 'JPEG', 'jpg', 'image/jpeg'
48 th = Image.alpha_composite(
49 Image.new('RGBA', th.size, '#fff'),
52 th = th.convert('RGB')
53 th.save(buffer, format=th_format)
56 file_name = 'image%d.%s' % (
57 builder.assign_image_number(),
62 content=buffer.getvalue(),
64 media_type=media_type,
69 'alt': self.attrib.get('alt', ''),
70 'title': self.attrib.get('alt', ''),
73 get_epub_attr = get_html_attr