From 1e040feb1b3c1147294a272b4c49fc6234494a47 Mon Sep 17 00:00:00 2001 From: wiredfool Date: Sun, 18 Jan 2015 10:56:29 -0800 Subject: [PATCH] Adjust buffer size when quality=keep, fixes #148 (again) --- PIL/JpegImagePlugin.py | 3 ++- Tests/test_file_jpeg.py | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/PIL/JpegImagePlugin.py b/PIL/JpegImagePlugin.py index 9dd79d5e6..8c20f5863 100644 --- a/PIL/JpegImagePlugin.py +++ b/PIL/JpegImagePlugin.py @@ -684,7 +684,8 @@ def _save(im, fp, filename): # https://github.com/jdriscoll/django-imagekit/issues/50 bufsize = 0 if "optimize" in info or "progressive" in info or "progression" in info: - if quality >= 95: + # keep sets quality to 0, but the actual value may be high. + if quality >= 95 or quality == 0: bufsize = 2 * im.size[0] * im.size[1] else: bufsize = im.size[0] * im.size[1] diff --git a/Tests/test_file_jpeg.py b/Tests/test_file_jpeg.py index b0f179d5f..64e8b74af 100644 --- a/Tests/test_file_jpeg.py +++ b/Tests/test_file_jpeg.py @@ -3,6 +3,7 @@ from helper import djpeg_available, cjpeg_available import random from io import BytesIO +import os from PIL import Image from PIL import ImageFile @@ -334,6 +335,24 @@ class TestFileJpeg(PillowTestCase): self.assertEqual(tag_ids['RelatedImageWidth'], 0x1001) self.assertEqual(tag_ids['RelatedImageLength'], 0x1002) + def test_MAXBLOCK_scaling(self): + def gen_random_image(size): + """ Generates a very hard to compress file + :param size: tuple + """ + return Image.frombytes('RGB',size, os.urandom(size[0]*size[1] *3)) + + im = gen_random_image((512,512)) + f = self.tempfile("temp.jpeg") + im.save(f, quality=100, optimize=True) + + reloaded = Image.open(f) + + # none of these should crash + reloaded.save(f, quality='keep') + reloaded.save(f, quality='keep', progressive=True) + reloaded.save(f, quality='keep', optimize=True) + if __name__ == '__main__': unittest.main()