Ticket #3848: django_core_validators_isValidImage.diff

File django_core_validators_isValidImage.diff, 1.7 KB (added by Andrew C. <andrewc-djangotrac1@…>, 18 years ago)
  • django/core/validators.py

     
    168168    """
    169169    from PIL import Image
    170170    from cStringIO import StringIO
     171    no_file_msg = gettext("No file was submitted. Check the encoding type on the form.")
     172    invalid_file_msg = gettext("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")
    171173    try:
    172174        content = field_data['content']
    173175    except TypeError:
    174         raise ValidationError, gettext("No file was submitted. Check the encoding type on the form.")
     176        raise ValidationError, no_file_msg
    175177    try:
    176         Image.open(StringIO(content))
    177     except IOError: # Python Imaging Library doesn't recognize it as an image
    178         raise ValidationError, gettext("Upload a valid image. The file you uploaded was either not an image or a corrupted image.")
     178        # load() is the only method that can spot a truncated JPEG,
     179        #  but it cannot be called sanely after verify()
     180        trial_image = Image.open(StringIO(content))
     181        trial_image.load()
     182        # verify() is the only method that can spot a corrupt PNG,
     183        #  but it must be called immediately after the constructor
     184        trial_image = Image.open(StringIO(content))
     185        trial_image.verify()
     186    except Exception, error:  # Too many exception types from PIL to enumerate properly
     187        message = invalid_file_msg
     188        if settings.DEBUG:
     189            message = message + "\n" + str(error)
     190        raise ValidationError(message)
    179191
    180192def isValidImageURL(field_data, all_data):
    181193    uc = URLMimeTypeCheck(('image/jpeg', 'image/gif', 'image/png'))
Back to Top