A custom FileSystemStorage made for normalizing extensions. It lets PIL look at the file to determine the format and append an always lower-case extension based on the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | from django.core.files.storage import FileSystemStorage
import os
class ImageFSStorage(FileSystemStorage):
"""
A FileSystemStorage which normalizes extensions for images.
"""
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
from PIL import ImageFile as PILImageFile
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 = basename if '.' not in basename else basename[:basename.rindex('.')]
basename = bare_basename + '.' + extension
name = os.path.join(dirname, basename)
return super(ImageFSStorage, self).save(name, content)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
_.replace('had', 'add'), hard to type in the morning :)
#
Sorry about the late reply, but you may absolutely!
#
Hm, scrap that, it seems it's just not working. There needs to be a content.seek(0) before the loop starts.
Also it might be a good idea to rewrite it to not being dependent on an image to be parsed. Right now it crashes with an exception in this case because im is undefined.
#
This does it for me:
#
Please login first before commenting.