summaryrefslogtreecommitdiff
path: root/storages/backends/image.py
diff options
context:
space:
mode:
authorYuval Adam <yuval@segmanta.com>2014-03-20 17:49:16 +0200
committerYuval Adam <yuval@segmanta.com>2014-03-20 17:49:16 +0200
commit75f93a3f7854a7383febd047391e2bfd4caceee0 (patch)
treed5e634ef292c6b84acacc3982dbcaa0d300a346e /storages/backends/image.py
Initial git fork of django-storagesHEADmaster
Diffstat (limited to 'storages/backends/image.py')
-rw-r--r--storages/backends/image.py55
1 files changed, 55 insertions, 0 deletions
diff --git a/storages/backends/image.py b/storages/backends/image.py
new file mode 100644
index 0000000..ccad24d
--- /dev/null
+++ b/storages/backends/image.py
@@ -0,0 +1,55 @@
+
+import os
+
+from django.core.files.storage import FileSystemStorage
+from django.core.exceptions import ImproperlyConfigured
+
+try:
+ from PIL import ImageFile as PILImageFile
+except ImportError:
+ raise ImproperlyConfigured("Could not load PIL dependency.\
+ \nSee http://www.pythonware.com/products/pil/")
+
+
+class ImageStorage(FileSystemStorage):
+ """
+ A FileSystemStorage which normalizes extensions for images.
+
+ Comes from http://www.djangosnippets.org/snippets/965/
+ """
+
+ def find_extension(self, format):
+ """Normalizes PIL-returned format into a standard, lowercase extension."""
+ format = format.lower()
+
+ if format == 'jpeg':
+ format = 'jpg'
+
+ return format
+
+ def save(self, name, content):
+ dirname = os.path.dirname(name)
+ basename = os.path.basename(name)
+
+ # Use PIL to determine filetype
+
+ p = PILImageFile.Parser()
+ while 1:
+ data = content.read(1024)
+ if not data:
+ break
+ p.feed(data)
+ if p.image:
+ im = p.image
+ break
+
+ extension = self.find_extension(im.format)
+
+ # Does the basename already have an extension? If so, replace it.
+ # bare as in without extension
+ bare_basename, _ = os.path.splitext(basename)
+ basename = bare_basename + '.' + extension
+
+ name = os.path.join(dirname, basename)
+ return super(ImageStorage, self).save(name, content)
+