Login

ImageFSStorage

Author:
vicvicvic
Posted:
August 12, 2008
Language:
Python
Version:
.96
Tags:
storage images
Score:
0 (after 0 ratings)

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

Comments

david_bgk (on August 14, 2008):
<p>_.replace('had', 'add'), hard to type in the morning :)</p>

#

vicvicvic (on September 5, 2008):
<p>Sorry about the late reply, but you may absolutely!</p>

#

olau (on May 29, 2009):
<p>Hm, scrap that, it seems it's just not working. There needs to be a content.seek(0) before the loop starts.</p> <p>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.</p>

#

jokull (on October 8, 2009):
<p>This does it for me:</p> <pre># 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) </pre>

#

Please login first before commenting.