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):
21 if self.attrib.get('wyrownanie'):
22 cls += ' ' + self.attrib['wyrownanie']
23 if self.attrib.get('oblew'):
27 'alt': self.attrib.get('alt', ''),
28 'title': self.attrib.get('alt', ''),
29 'src': self.attrib.get('src', ''),
31 if self.attrib.get('srcset'):
32 attr['srcset'] = self.attrib['srcset']
34 (min-width: 718px) 600px,
35 (min-width: 600px) calc(100vw - 118px),
36 (min-width: 320px) calc(100vw - 75px),
37 (min-width: 15em) calc(100wv - 60px),
40 if self.attrib.get('szer'):
41 attr['style'] = 'width: ' + self.attrib['szer']
44 def get_epub_attr(self, builder):
45 url = urllib.parse.urljoin(
50 imgfile = urllib.request.urlopen(url)
51 img = Image.open(imgfile)
52 th_format, ext, media_type = {
53 'GIF': ('GIF', 'gif', 'image/gif'),
54 'PNG': ('PNG', 'png', 'image/png'),
55 }.get(img.format, ('JPEG', 'jpg', 'image/jpeg'))
58 if img.size[0] < width:
61 th = img.resize((width, round(width * img.size[1] / img.size[0])))
64 th.save(buffer, format=th_format)
66 # Limit PNG to 200K. If larger, convert to JPEG.
67 if th_format == 'PNG' and buffer.tell() > MAX_PNG_WEIGHT:
68 th_format, ext, media_type = 'JPEG', 'jpg', 'image/jpeg'
71 th = Image.alpha_composite(
72 Image.new('RGBA', th.size, '#fff'),
75 th = th.convert('RGB')
76 th.save(buffer, format=th_format)
79 file_name = 'image%d.%s' % (
80 builder.assign_image_number(),
85 content=buffer.getvalue(),
87 media_type=media_type,
92 'alt': self.attrib.get('alt', ''),
93 'title': self.attrib.get('alt', ''),