Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

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.
  • Loading branch information...
1 parent bacb097 commit 3aa4b8165da23a2f094d0eeffacbda5484f4c1f6 @bak1an bak1an committed with apollo13
14 django/core/files/
@@ -4,7 +4,11 @@
Requires PIL, as you might imagine.
+import zlib
+import sys
from django.core.files import File
+from django.utils import six
class ImageFile(File):
@@ -55,7 +59,15 @@ def get_image_dimensions(file_or_path, close=False):
data =
if not data:
- 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"):
@claudep Collaborator
claudep added a note

Raises: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
You should probably use e.args[0] here.

@apollo13 Owner
apollo13 added a note

Hrmpf, why doesn't my python show those :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ pass
+ else:
+ six.reraise(*sys.exc_info())
@claudep Collaborator
claudep added a note

or simply raise ?
Generally, reraising is interesting when you want to modify exception parameters.

@apollo13 Owner
apollo13 added a note

sigh I shouldn't touch Django today I guess :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
if p.image:
return p.image.size
chunk_size = chunk_size*2
BIN  tests/regressiontests/file_storage/magic.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 tests/regressiontests/file_storage/
@@ -7,6 +7,7 @@
import sys
import tempfile
import time
+import zlib
from datetime import datetime, timedelta
from io import BytesIO
@@ -559,6 +560,20 @@ def test_multiple_calls(self):
self.assertEqual(image_pil.size, size_1)
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:
+"Exception raised from get_image_dimensions().")
+ self.assertEqual(size,
class ContentFileTestCase(unittest.TestCase):
def setUp(self):

0 comments on commit 3aa4b81

Please sign in to comment.
Something went wrong with that request. Please try again.