I have a model that has a ImageField, and I uploaded a sample image of
35 megs. This image will be used at different places and resized for
those different purposes.


I noticed that the django.core.files.images --> get_image_dimensions
seems to be slow.
It took more than an hour and a half to process that image by
get_image_dimensions (I suspect the read(1024) being the cause)

So, i decided to attempt to optimize it.

Warning: I'm really not good in Python, so suggestions are welcome.
The code is inspired by django.forms.fields.ImageField


Here's the code. PS: I'm not going to create a patch, because I really
don't know how to. I do welcome anyone using this to create a patch
tho! :)

def get_image_dimensions(file_or_path):
    """Returns the (width, height) of an image, given an open file or
a path."""
    from PIL import ImageFile as PILImageFile
    from PIL import Image
    p = PILImageFile.Parser()

    """
    NEW
    """

    if hasattr(file_or_path, 'read'):
        file = StringIO(file_or_path.read())
    else:
        file = open(file_or_path, 'rb')
        file = StringIO(file.read())
    try:
        trial_image = Image.open(file)
        trial_image.load()
        if hasattr(file, 'reset'):
                file.reset()
        if trial_image:
            return trial_image.size


    except ImportError:
        raise

    return None

    """
    OLD
    """
    """
    if hasattr(file_or_path, 'read'):
        file = file_or_path
    else:
        file = open(file_or_path, 'rb')
    while 1:
        data = file.read(1024)
        if not data:
            break
        p.feed(data)
        if p.image:
            return p.image.size
    return None
    """

Please let me know what you think of the change.


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to