Ticket #8817: 8817_2.diff

File 8817_2.diff, 2.3 KB (added by Harm Geerts, 16 years ago)

changed patch to reset the file position before and after reading the dimensions. Without these changes the Model.save() would fail if the file position was non zero, for example by validating the image dimensions in a forms clean method.

  • django/core/files/images.py

     
    2828    """Returns the (width, height) of an image, given an open file or a path."""
    2929    from PIL import ImageFile as PILImageFile
    3030    p = PILImageFile.Parser()
    31     if hasattr(file_or_path, 'read'):
     31    local_file = True
     32    # If we have a file name, prefer to open a new file to avoid modifying the
     33    # state of the file object we were given.
     34    if hasattr(file_or_path, 'name'):
     35        # If this is a FileField, use custom storage backend to re-open file
     36        if hasattr(file_or_path, 'storage'):
     37            file = file_or_path.storage.open(file_or_path.name, 'rb')
     38        else:
     39            file = open(file_or_path.name, 'rb')
     40    elif hasattr(file_or_path, 'read'):
    3241        file = file_or_path
     42        local_file = False
     43        if file.tell() != 0:
     44            file.seek(0)
    3345    else:
    3446        file = open(file_or_path, 'rb')
    3547    while 1:
     
    3850            break
    3951        p.feed(data)
    4052        if p.image:
     53            if local_file:
     54                file.close()
     55            else:
     56                file.seek(0)
    4157            return p.image.size
     58    if local_file:
     59        file.close()
     60    else:
     61        file.seek(0)
    4262    return None
  • tests/regressiontests/file_storage/models.py

     
    8484>>> hasattr(p3.mugshot, '_file')
    8585False
    8686
     87# Bug #8817: ImageField.width and ImageField.height should not leave the file open
     88>>> _ = p3.mugshot.width
     89>>> hasattr(p3.mugshot, '_file')
     90False
     91
     92>>> _ = p3.mugshot.height
     93>>> hasattr(p3.mugshot, '_file')
     94False
     95
     96# get_image_dimensions is used to populate the width/height fields
     97# and should not fail if the file position is not 0
     98# or leave the position at the end of the file
     99>>> from django.core.files.images import get_image_dimensions
     100>>> f = ContentFile(image_data)
     101>>> f.seek(1)
     102>>> get_image_dimensions(f)
     103(16, 16)
     104>>> f.tell()
     1050
     106
    87107>>> shutil.rmtree(temp_storage_dir)
    88108"""}
    89109
Back to Top