|
Revision 8249, 1.1 kB
(checked in by jacob, 4 months ago)
|
Don't import PIL until needed so that systems without PIL don't barf.
|
| Line | |
|---|
| 1 |
""" |
|---|
| 2 |
Utility functions for handling images. |
|---|
| 3 |
|
|---|
| 4 |
Requires PIL, as you might imagine. |
|---|
| 5 |
""" |
|---|
| 6 |
|
|---|
| 7 |
from django.core.files import File |
|---|
| 8 |
|
|---|
| 9 |
class ImageFile(File): |
|---|
| 10 |
""" |
|---|
| 11 |
A mixin for use alongside django.core.files.base.File, which provides |
|---|
| 12 |
additional features for dealing with images. |
|---|
| 13 |
""" |
|---|
| 14 |
def _get_width(self): |
|---|
| 15 |
return self._get_image_dimensions()[0] |
|---|
| 16 |
width = property(_get_width) |
|---|
| 17 |
|
|---|
| 18 |
def _get_height(self): |
|---|
| 19 |
return self._get_image_dimensions()[1] |
|---|
| 20 |
height = property(_get_height) |
|---|
| 21 |
|
|---|
| 22 |
def _get_image_dimensions(self): |
|---|
| 23 |
if not hasattr(self, '_dimensions_cache'): |
|---|
| 24 |
self._dimensions_cache = get_image_dimensions(self) |
|---|
| 25 |
return self._dimensions_cache |
|---|
| 26 |
|
|---|
| 27 |
def get_image_dimensions(file_or_path): |
|---|
| 28 |
"""Returns the (width, height) of an image, given an open file or a path.""" |
|---|
| 29 |
from PIL import ImageFile as PILImageFile |
|---|
| 30 |
p = PILImageFile.Parser() |
|---|
| 31 |
if hasattr(file_or_path, 'read'): |
|---|
| 32 |
file = file_or_path |
|---|
| 33 |
else: |
|---|
| 34 |
file = open(file_or_path, 'rb') |
|---|
| 35 |
while 1: |
|---|
| 36 |
data = file.read(1024) |
|---|
| 37 |
if not data: |
|---|
| 38 |
break |
|---|
| 39 |
p.feed(data) |
|---|
| 40 |
if p.image: |
|---|
| 41 |
return p.image.size |
|---|
| 42 |
return None |
|---|