Ticket #11158: 11158-combined.diff

File 11158-combined.diff, 2.4 KB (added by jkocherhans, 15 years ago)

Merged SmilyChris's patch and SAn's tests into a single patch.

  • django/core/files/images.py

    diff --git a/django/core/files/images.py b/django/core/files/images.py
    index 55008b5..ab9a398 100644
    a b class ImageFile(File):  
    2323        if not hasattr(self, '_dimensions_cache'):
    2424            close = self.closed
    2525            self.open()
    26             self._dimensions_cache = get_image_dimensions(self)
    27             if close:
    28                 self.close()
     26            self._dimensions_cache = get_image_dimensions(self, close=close)
    2927        return self._dimensions_cache
    3028
    31 def get_image_dimensions(file_or_path):
     29def get_image_dimensions(file_or_path, close=False):
    3230    """Returns the (width, height) of an image, given an open file or a path."""
    3331    # Try to import PIL in either of the two ways it can end up installed.
    3432    try:
    def get_image_dimensions(file_or_path):  
    3735        import ImageFile as PILImageFile
    3836       
    3937    p = PILImageFile.Parser()
    40     close = False
    4138    if hasattr(file_or_path, 'read'):
    4239        file = file_or_path
     40        file_pos = file.tell()
     41        file.seek(0)
    4342    else:
    4443        file = open(file_or_path, 'rb')
    4544        close = True
    def get_image_dimensions(file_or_path):  
    5554    finally:
    5655        if close:
    5756            file.close()
     57        else:
     58            file.seek(file_pos)
  • tests/regressiontests/file_storage/tests.py

    diff --git a/tests/regressiontests/file_storage/tests.py b/tests/regressiontests/file_storage/tests.py
    index 2c5f0f4..a1470f9 100644
    a b if Image is not None:  
    230230            finally:
    231231                del images.open
    232232            self.assert_(FileWrapper._closed)
     233
     234    class InconsistentGetImageDimensionsBug(TestCase):
     235        """
     236        Test that get_image_dimensions() works properly after various calls using a file handler (#11158)
     237        """
     238        def test_multiple_calls(self):
     239            """
     240            Multiple calls of get_image_dimensions() should return the same size.
     241            """
     242            from django.core.files.images import ImageFile
     243            img_path = os.path.join(os.path.dirname(__file__), "test.png")
     244            image = ImageFile(open(img_path))
     245            image_pil = Image.open(img_path)
     246            size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
     247            self.assertEqual(image_pil.size, size_1)
     248            self.assertEqual(size_1, size_2)
Back to Top