app/django/core/files/images.py
author Pawel Solyga <Pawel.Solyga@gmail.com>
Mon, 18 May 2009 14:05:38 +0200
changeset 2322 98fe07a5542f
parent 323 ff1a9aa48cfd
permissions -rw-r--r--
Add acceptedStudentsCSVExport function to stats.py script. This funtion is used to generate CSV with all accepted students. It still needs some work and I left TODOs there. I also added helper function for saving data to CSV, which can be reused for other kinds of reports.

"""
Utility functions for handling images.

Requires PIL, as you might imagine.
"""

from django.core.files import File

class ImageFile(File):
    """
    A mixin for use alongside django.core.files.base.File, which provides
    additional features for dealing with images.
    """
    def _get_width(self):
        return self._get_image_dimensions()[0]
    width = property(_get_width)

    def _get_height(self):
        return self._get_image_dimensions()[1]
    height = property(_get_height)

    def _get_image_dimensions(self):
        if not hasattr(self, '_dimensions_cache'):
            self._dimensions_cache = get_image_dimensions(self)
        return self._dimensions_cache

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
    p = PILImageFile.Parser()
    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