Fixed #19457 -- ImageField size detection failed for some files.

This was caused by PIL raising a zlib truncated stream error since we fed
the parser with chunks instead of the whole image.
This commit is contained in:
Anton Baklanov 2012-12-13 18:26:34 +02:00 committed by Florian Apolloner
parent bacb097ac3
commit 3aa4b8165d
3 changed files with 28 additions and 1 deletions

View File

@ -4,7 +4,11 @@ Utility functions for handling images.
Requires PIL, as you might imagine. Requires PIL, as you might imagine.
""" """
import zlib
import sys
from django.core.files import File from django.core.files import File
from django.utils import six
class ImageFile(File): class ImageFile(File):
""" """
@ -55,7 +59,15 @@ def get_image_dimensions(file_or_path, close=False):
data = file.read(chunk_size) data = file.read(chunk_size)
if not data: if not data:
break break
p.feed(data) try:
p.feed(data)
except zlib.error as e:
# ignore zlib complaining on truncated stream, just feed more
# data to parser (ticket #19457).
if e.message.startswith("Error -5"):
pass
else:
six.reraise(*sys.exc_info())
if p.image: if p.image:
return p.image.size return p.image.size
chunk_size = chunk_size*2 chunk_size = chunk_size*2

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

View File

@ -7,6 +7,7 @@ import shutil
import sys import sys
import tempfile import tempfile
import time import time
import zlib
from datetime import datetime, timedelta from datetime import datetime, timedelta
from io import BytesIO from io import BytesIO
@ -559,6 +560,20 @@ class InconsistentGetImageDimensionsBug(unittest.TestCase):
self.assertEqual(image_pil.size, size_1) self.assertEqual(image_pil.size, size_1)
self.assertEqual(size_1, size_2) self.assertEqual(size_1, size_2)
@unittest.skipUnless(Image, "PIL not installed")
def test_bug_19457(self):
"""
Regression test for #19457
get_image_dimensions fails on some pngs, while Image.size is working good on them
"""
img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
try:
size = get_image_dimensions(img_path)
except zlib.error:
self.fail("Exception raised from get_image_dimensions().")
self.assertEqual(size, Image.open(img_path).size)
class ContentFileTestCase(unittest.TestCase): class ContentFileTestCase(unittest.TestCase):
def setUp(self): def setUp(self):