X-Git-Url: https://git.mdrn.pl/librarian.git/blobdiff_plain/3a0c83394d5783715fab2be29fa1a9cfc3574e28..eb25cada3f68db8f58689bff431edd321620fd72:/src/librarian/elements/figures/ilustr.py?ds=sidebyside diff --git a/src/librarian/elements/figures/ilustr.py b/src/librarian/elements/figures/ilustr.py index 33099f6..51bae4e 100644 --- a/src/librarian/elements/figures/ilustr.py +++ b/src/librarian/elements/figures/ilustr.py @@ -8,14 +8,40 @@ from PIL import Image from ..base import WLElement +MAX_PNG_WEIGHT = 200000 + + class Ilustr(WLElement): - SHOULD_HAVE_ID = True + NUMBERING = 'i' EPUB_TAG = HTML_TAG = 'img' def get_html_attr(self, builder): - ## TODO: thumbnail. + cls = 'ilustr' + if self.attrib.get('wyrownanie'): + cls += ' ' + self.attrib['wyrownanie'] + if self.attrib.get('oblew'): + cls += ' oblew' + attr = { + 'class': cls, + 'alt': self.attrib.get('alt', ''), + 'title': self.attrib.get('alt', ''), + 'src': self.attrib.get('src', ''), + } + if self.attrib.get('srcset'): + attr['srcset'] = self.attrib['srcset'] + attr['sizes'] = ''' + (min-width: 718px) 600px, + (min-width: 600px) calc(100vw - 118px), + (min-width: 320px) calc(100vw - 75px), + (min-width: 15em) calc(100wv - 60px), + calc(100wv - 40px) + ''' + if self.attrib.get('szer'): + attr['style'] = 'width: ' + self.attrib['szer'] + return attr + def get_epub_attr(self, builder): url = urllib.parse.urljoin( builder.base_url, self.get('src') @@ -28,7 +54,7 @@ class Ilustr(WLElement): 'PNG': ('PNG', 'png', 'image/png'), }.get(img.format, ('JPEG', 'jpg', 'image/jpeg')) - width = 1200 + width = 600 if img.size[0] < width: th = img else: @@ -36,6 +62,19 @@ class Ilustr(WLElement): buffer = io.BytesIO() th.save(buffer, format=th_format) + + # Limit PNG to 200K. If larger, convert to JPEG. + if th_format == 'PNG' and buffer.tell() > MAX_PNG_WEIGHT: + th_format, ext, media_type = 'JPEG', 'jpg', 'image/jpeg' + if th.mode != 'RGB': + buffer = io.BytesIO() + th = Image.alpha_composite( + Image.new('RGBA', th.size, '#fff'), + th.convert('RGBA') + ) + th = th.convert('RGB') + th.save(buffer, format=th_format) + imgfile.close() file_name = 'image%d.%s' % ( builder.assign_image_number(), @@ -53,5 +92,3 @@ class Ilustr(WLElement): 'alt': self.attrib.get('alt', ''), 'title': self.attrib.get('alt', ''), } - - get_epub_attr = get_html_attr