Check mode when generating JPEG thumbnails and watermarks
authorThierry Florac <thierry.florac@onf.fr>
Thu, 11 Jan 2018 17:17:30 +0100
changeset 75 b5c2949e7f44
parent 74 56efd637473e
child 76 5dc430f8bdcf
Check mode when generating JPEG thumbnails and watermarks
src/pyams_file/image.py
src/pyams_file/watermark.py
--- a/src/pyams_file/image.py	Thu Jan 11 17:15:42 2018 +0100
+++ b/src/pyams_file/image.py	Thu Jan 11 17:17:30 2018 +0100
@@ -85,7 +85,10 @@
             format = 'JPEG'
         # check image mode
         if image.mode == 'P':
-            image = image.convert('RGBA')
+            if format == 'JPEG':
+                image = image.convert('RGB')
+            else:
+                image = image.convert('RGBA')
         # generate thumbnail
         new_image = BytesIO()
         image.resize((width, height), Image.ANTIALIAS) \
@@ -128,7 +131,10 @@
             format = 'JPEG'
         # check image mode
         if image.mode == 'P':
-            image = image.convert('RGBA')
+            if format == 'JPEG':
+                image = image.convert('RGB')
+            else:
+                image = image.convert('RGBA')
         # generate thumbnail
         new_image = BytesIO()
         thumb_size = self.get_thumb_size(width, height, geometry)
--- a/src/pyams_file/watermark.py	Thu Jan 11 17:15:42 2018 +0100
+++ b/src/pyams_file/watermark.py	Thu Jan 11 17:17:30 2018 +0100
@@ -89,5 +89,8 @@
             layer.paste(watermark, position)
         # composite the watermark with the layer
         new = BytesIO()
-        Image.composite(layer, image, layer).save(new, format)
+        composite = Image.composite(layer, image, layer)
+        if format == 'JPEG':
+            composite = composite.convert('RGB')
+        composite.save(new, format)
         return new.getvalue(), format.lower()