ImageFSStorage

 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

  1. FileField with file extension whitelist by jedie 5 years, 8 months ago
  2. jinja2 csrf_token extension by jasongreen 4 years, 3 months ago
  3. Improve ajax progress bar by jquery extensions by williamcai 3 years, 4 months ago
  4. Strip trailing .html extensions from URLs so that existing bookmarks work for a legacy site ported to Django by daverowell 6 years, 11 months ago
  5. ManyToManyField with maximum cardinality constraints by gsakkis 3 years, 10 months ago

Comments

david_bgk (on August 14, 2008):

_.replace('had', 'add'), hard to type in the morning :)

#

vicvicvic (on September 5, 2008):

Sorry about the late reply, but you may absolutely!

#

olau (on May 29, 2009):

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.

#

jokull (on October 8, 2009):

This does it for me:

# Use PIL to determine filetype
from PIL import ImageFile as PILImageFile
p = PILImageFile.Parser()

for data in content.chunks():
    p.feed(data)
    if p.image:
        format = p.image.format
        break
else:
    format = 'jpg' # Wild guess

extension = self.find_extension(format)

#

(Forgotten your password?)