import os

from PIL import Image

from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy  as _
from django.conf import settings


def validate_image_format(f):
    # Check file extension
    extension = os.path.splitext(f.name)[1].lower()[1:]

    if extension == 'jpg':
        extension = 'jpeg'

    if extension not in ['gif', 'jpeg', 'png']:
        raise ValidationError(_("Not a valid image. Please use a gif, jpeg or png file with the correct file extension."))

    if f.closed:
        # Reopen the file
        file = open(os.path.join(settings.MEDIA_ROOT, f.name), 'rb')
        close = True
    else:
        # Seek to first byte but save position to be restored later
        file_position = f.tell()
        f.seek(0)
        file = f
        close = False

    # Open image file
    image = Image.open(file)

    # Check that the internal format matches the extension
    if image.format.upper() != extension.upper():
        raise ValidationError(_("Not a valid %s image. Please use a gif, jpeg or png file with the correct file extension.") % (extension.upper()))

    # Close/restore file
    if close:
        file.close()
    else:
        f.seek(file_position)

@@ -139,41 +139,8 @@
 s _%0A
-from django.conf import settings%0A
 %0A%0Ade
@@ -486,223 +486,30 @@
     
-if f.closed:%0A        # Reopen the file%0A        file = open(os.path.join(settings.MEDIA_ROOT, f.name), 'rb')%0A        close = True%0A    else:%0A        # Seek to first byte but save position to be restored later%0A 
+# Open image file%0A
     
-   
 file
@@ -529,20 +529,16 @@
 .tell()%0A
-    
     f.se
@@ -551,93 +551,54 @@
     
-    file = f%0A        close = False%0A%0A    # Open image file%0A    image = Image.open(file
+image = Image.open(f)%0A    f.seek(file_position
 )%0A%0A 
@@ -857,105 +857,4 @@
 )))%0A
-%0A    # Close/restore file%0A    if close:%0A        file.close()%0A    else:%0A        f.seek(file_position)%0A

Revert "Reopen images for validation if they are closed"