diff --git a/sqlalchemy_media/processors.py b/sqlalchemy_media/processors.py index 57734e0..00cd802 100644 --- a/sqlalchemy_media/processors.py +++ b/sqlalchemy_media/processors.py @@ -394,8 +394,13 @@ def process(self, descriptor: StreamDescriptor, context: dict): # Cropping if self.crop: img = img.crop(self.crop) - - img.save(output_buffer, format=format_) + try: + img.save(output_buffer, format=format_) + except (OSError): + if img.mode in ("RGBA", "P"): + img = img.convert("RGB") + img.save(output_buffer, format=format_) + self._update_context(img, format_, context) output_buffer.seek(0) descriptor.replace(output_buffer, position=0, **context) diff --git a/sqlalchemy_media/tests/stuff/rgba-cat.png b/sqlalchemy_media/tests/stuff/rgba-cat.png new file mode 100644 index 0000000..b31a948 Binary files /dev/null and b/sqlalchemy_media/tests/stuff/rgba-cat.png differ diff --git a/sqlalchemy_media/tests/test_image_processors.py b/sqlalchemy_media/tests/test_image_processors.py index 2454e61..99eb57a 100644 --- a/sqlalchemy_media/tests/test_image_processors.py +++ b/sqlalchemy_media/tests/test_image_processors.py @@ -14,6 +14,7 @@ def setUpClass(cls): cls.stuff_path = join(cls.this_dir, 'stuff') cls.cat_jpeg = join(cls.stuff_path, 'cat.jpg') cls.cat_png = join(cls.stuff_path, 'cat.png') + cls.cat_png_alpha = join(cls.stuff_path, 'rgba-cat.png') cls.dog_jpg = join(cls.stuff_path, 'dog_213X160.jpg') def test_resize_reformat(self): @@ -32,6 +33,20 @@ def test_resize_reformat(self): 'height': 150, 'extension': '.jpg' }) + + with AttachableDescriptor(self.cat_png_alpha) as d: + ctx = dict( + length=100000, + extension='.jpg', + ) + ImageProcessor(fmt='jpeg', width=200).process(d, ctx) + + self.assertDictEqual(ctx, { + 'content_type': 'image/jpeg', + 'width': 200, + 'height': 150, + 'extension': '.jpg' + }) with AttachableDescriptor(self.cat_jpeg) as d: # Checking when not modifying stream.