Limit image size, fixes #4464. master 24.5
authorRadek Czajka <rczajka@rczajka.pl>
Wed, 22 May 2024 09:47:40 +0000 (11:47 +0200)
committerRadek Czajka <rczajka@rczajka.pl>
Wed, 22 May 2024 09:47:40 +0000 (11:47 +0200)
CHANGELOG.md
setup.py
src/librarian/document.py
src/librarian/elements/figures/ilustr.py
src/librarian/pdf.py

index 171bb9b..13a3341 100644 (file)
@@ -2,6 +2,11 @@
 
 This document records all notable changes to Librarian.
 
+## 24.5
+
+- Smaller images in EPUB (600px width instead of 1200px).
+- Convert PNG to JPEGs if too large in EPUBs.
+
 ## 24.4
 
 - Add fundraising inserts in PDF.
index 1368375..494b3f2 100755 (executable)
--- a/setup.py
+++ b/setup.py
@@ -22,7 +22,7 @@ def whole_tree(prefix, path):
 
 setup(
     name='librarian',
-    version='24.4',
+    version='24.5',
     description='Converter from WolneLektury.pl XML-based language to XHTML, TXT and other formats',
     author="Marek StÄ™pniowski",
     author_email='marek@stepniowski.com',
index 2e9a4a5..7780b61 100644 (file)
@@ -81,6 +81,7 @@ class WLDocument:
         """
         EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE)
         def _compat_assign_ordered_ids_in_elem(elem, i):
+            if isinstance(elem, etree._Comment): return i
             elem.attrib['_compat_ordered_id'] = str(i)
             i += 1
             if getattr(elem, 'HTML_CLASS', None) == 'stanza':
index 33099f6..4e848ac 100644 (file)
@@ -8,6 +8,9 @@ from PIL import Image
 from ..base import WLElement
 
 
+MAX_PNG_WEIGHT = 200000
+
+
 class Ilustr(WLElement):
     SHOULD_HAVE_ID = True
 
@@ -28,7 +31,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 +39,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(),
index e5cf5bd..de09755 100644 (file)
@@ -196,7 +196,7 @@ def add_fundraising(doc, fundraising):
         naglowek.addprevious(spot)
         spots.append(spot)
     spot = etree.Element('f_spot')
-    doc.getroot()[-1][-1].append(spot)
+    doc.getroot()[-1].append(spot)
     spots.append(spot)
     e = len(spots)
     nfunds = len(fundraising)