Permalink
Browse files

Merge pull request #2010 from uploadcare/jpeg-raise-on-alpha

Show warning when trying to save RGBA image as JPEG
  • Loading branch information...
2 parents 5d2667e + 193c756 commit e980ca7896249e32b40a25c0860c093ec5cb3a90 @wiredfool wiredfool committed on GitHub Aug 25, 2016
Showing with 29 additions and 2 deletions.
  1. +8 −0 PIL/JpegImagePlugin.py
  2. +2 −2 Tests/helper.py
  3. +19 −0 Tests/test_file_jpeg.py
@@ -583,6 +583,14 @@ def _save(im, fp, filename):
except KeyError:
raise IOError("cannot write mode %s as JPEG" % im.mode)
+ if im.mode == 'RGBA':
+ warnings.warn(
+ 'You are saving RGBA image as JPEG. The alpha channel will be '
+ 'discarded. This conversion is deprecated and will be disabled '
+ 'in Pillow 3.7. Please, convert the image to RGB explicitly.',
+ DeprecationWarning
+ )
+
info = im.encoderinfo
dpi = info.get("dpi", (0, 0))
View
@@ -99,7 +99,7 @@ def assert_image_similar(self, a, b, epsilon, msg=None):
" average pixel value difference %.4f > epsilon %.4f" % (
ave_diff, epsilon))
- def assert_warning(self, warn_class, func):
+ def assert_warning(self, warn_class, func, *args, **kwargs):
import warnings
result = None
@@ -108,7 +108,7 @@ def assert_warning(self, warn_class, func):
warnings.simplefilter("always")
# Hopefully trigger a warning.
- result = func()
+ result = func(*args, **kwargs)
# Verify some things.
self.assertGreaterEqual(len(w), 1)
@@ -450,6 +450,25 @@ def test_bad_mpo_header(self):
# Assert
self.assertEqual(im.format, "JPEG")
+ def test_save_correct_modes(self):
+ out = BytesIO()
+ for mode in ['1', 'L', 'RGB', 'RGBX', 'CMYK', 'YCbCr']:
+ img = Image.new(mode, (20, 20))
+ img.save(out, "JPEG")
+
+ def test_save_wrong_modes(self):
+ out = BytesIO()
+ for mode in ['LA', 'La', 'RGBa', 'P']:
+ img = Image.new(mode, (20, 20))
+ self.assertRaises(IOError, img.save, out, "JPEG")
+
+ def test_save_modes_with_warnings(self):
+ # ref https://github.com/python-pillow/Pillow/issues/2005
+ out = BytesIO()
+ for mode in ['RGBA']:
+ img = Image.new(mode, (20, 20))
+ self.assert_warning(DeprecationWarning, img.save, out, "JPEG")
+
if __name__ == '__main__':
unittest.main()

0 comments on commit e980ca7

Please sign in to comment.