django-storages / django_storages /

import os
from PIL import ImageFile as PILImageFile
from import FileSystemStorage

__all__ = ('ImageStorage',)

class ImageStorage(FileSystemStorage):
    A FileSystemStorage which normalizes extensions for images.

    Comes from

    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 =
            if not data:
            if p.image:
                im = p.image

        extension = self.find_extension(im.format)

        # Does the basename already have an extension? If so, replace it.
        bare_basename, _ = os.path.splitext(basename)
        basename = bare_basename + '.' + extension

        name = os.path.join(dirname, basename)
        return super(ImageStorage, self).save(name, content)